我正在为一个带有异步服务的组件编写Angular 7单元测试用例,但是遇到了以下错误:
错误:预期spy create已被调用一次。它被调用了0次。
这是我的组件:
export class RegistrationComponent implements OnInit {
submitRegistrationForm() {
if (this.profileForm.invalid) {
this.validateAllFields(this.profileForm);
} else {
// send a http request to save this data
this.guestUserService.create(this.profileForm.value).subscribe(
result => {
if (result) {
console.log('result', result);
this.router.navigate(['/login']);
}
},
error => {
console.log('error', error);
});
}
}
单元测试用例:
describe('RegistrationComponent', () => {
let component: RegistrationComponent;
let fixture: ComponentFixture<RegistrationComponent>;
let myService;
let mySpy;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [RegistrationComponent],
imports: [ ],
providers: [
{ provide: GuestUserService, useValue: new MyServiceStub() }]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(RegistrationComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should submit Registration Form', async(inject([Router], (router) => {
myService = TestBed.get(GuestUserService);
mySpy = spyOn(myService, 'create');
spyOn(router, 'navigate');
spyOn(component, 'submitRegistrationForm');
component.profileForm.controls['firstName'].setValue('Arjun');
component.profileForm.controls['lastName'].setValue('Singh');
component.profileForm.controls['password'].setValue('12345678');
component.profileForm.controls['confirmPassword'].setValue('12345678');
component.submitRegistrationForm();
expect(component.profileForm.invalid).toBe(false);
expect(component.submitRegistrationForm).toHaveBeenCalled();
expect(myService).toBeDefined();
expect(mySpy).toBeDefined();
expect(mySpy).toHaveBeenCalledTimes(1); // Getting error is this
expect(router.navigate).toHaveBeenCalled();
})
));
我尝试在beforeEach中移动spy的减速,但仍然出现相同的错误。
如何修复此错误?
谢谢!
expect(myService.create).toHaveBeenCalledTimes(1);
- user2216584detectChanges
或者注入done
并调用它。 - The Head Rushconsole.log
并查看记录了什么。从你的测试用例来看,似乎你的组件的this.profileForm
是无效的,因此你的submitRegistrationForm
方法的 else 条件没有被执行。你确定submitRegistrationForm
的 else 条件被调用了吗?放置日志并检查。 - user2216584