Currently, I am in the process of writing unit test cases for an Angular 7 Component that utilizes an async service. Unfortunately, I encountered the following error:
Error: Expected spy create to have been called once. It was called 0 times.
Below is the code snippet for my Component:
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);
});
}
}
Unit test case excerpt:
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); // Receiving above error here
expect(router.navigate).toHaveBeenCalled();
})
));
Even after trying to relocate the spy declaration within beforeEach, I am still encountering the same error message. Can anyone provide guidance on how to resolve this issue?
Thank you!