【发布时间】:2021-10-09 02:01:39
【问题描述】:
我有一个 Angular 组件和一个服务。在组件中,我有一个调用服务的一个方法的方法。在组件测试中,我尝试为服务创建一个模拟,然后当我调用组件的方法时,我想检查是否从组件调用了服务方法。
组件:
export class TestComponent {
constructor(private testService: TestService) {}
edit(): void {
this.testService.getCase('id').subscribe(console.log);
}
}
服务:
@Injectable({
providedIn: 'root'
})
export class TestService {
constructor(
private http: HttpClient,
) { }
getCase(id: string): Observable<any> {
return this.http.get<any>(`url`);
}
}
还有测试:
describe('TestComponent', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
const testServiceMock = jasmine.createSpyObj('TestService', ['getCase']);
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ TestComponent ],
providers: [
{ provide: TestService, useValue: testServiceMock },
]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('expect service has been called', () => {
spyOn(component, 'edit');
component.edit();
expect(component.edit).toHaveBeenCalledTimes(1);
expect(testServiceMock.getCase).toHaveBeenCalled();
});
});
这条线总是失败:expect(testServiceMock.getCase).toHaveBeenCalled();
TestComponent expect service has been called FAILED Error: Expected spy TestService.getCase to have been called.
【问题讨论】:
标签: angular unit-testing jasmine