我有以下组件和规范文件,尝试测试命中 API 端点并基于 id 返回字符串的服务调用。根据我传入的
employerId
,我希望返回“注册雇主”并将其设置为 employerName
。该测试总是失败并出现错误 Expected undefined to be 'Enrollment Employer'
我可以调试并查看传递给 getEmployerName() 的正确
employerId
,但我没有收到响应。我正确地编写了这个测试吗?
规格:
beforeEach(() => {
fixture = TestBed.createComponent(EnrollmentComponent);
component = fixture.componentInstance;
debugElement = fixture.debugElement;
employerService = debugElement.injector.get(EmployerService);
employerSpy = spyOn(employerService, 'getEmployerName').and.callThrough();
fixture.detectChanges();
});
it('should call the employer service and return the employer name', () => {
component.employerId = 12485;
component.getEmployerName();
expect(employerSpy).toHaveBeenCalled();
expect(component.employerName).toBe('Enrollment Employer');
})
成分:
getEmployerName() {
this.employerService.getEmployerName(this.employerId).subscribe(res => {
this.employerName = res.empName;
});
}
服务:
getEmployerName(employerId: number) {
const url = `${this.url}getEmployerName?employerId=${employerId}`
return this.apiService.request<any>({ url, method: HttpReqMethod.GET })
}
您可以使用
fakeAsync
和flush
等待API调用。
it('should call the employer service and return the employer name', fakeAsync(() => {
component.employerId = 12485;
component.getEmployerName();
flush();
expect(employerSpy).toHaveBeenCalled();
expect(component.employerName).toBe('Enrollment Employer');
}));
您还可以伪造 API 调用以节省时间!
beforeEach(() => {
fixture = TestBed.createComponent(EnrollmentComponent);
component = fixture.componentInstance;
debugElement = fixture.debugElement;
employerService = debugElement.injector.get(EmployerService);
employerSpy = spyOn(employerService, 'getEmployerName').and.returnValue(of({empName: 'test'}));
fixture.detectChanges();
});
it('should call the employer service and return the employer name', fakeAsync(() => {
component.employerId = 12485;
component.getEmployerName();
flush();
expect(employerSpy).toHaveBeenCalled();
expect(component.employerName).toBe('Enrollment Employer');
}));