190
rated 0 times
[
195]
[
5]
/ answers: 1 / hits: 50540
/ 5 Years ago, tue, june 18, 2019, 12:00:00
I'm writing unit test cases in angular 7 for a Component with async service and getting this error:
Error: Expected spy create to have been called once. It was called 0
times.
Here is 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:
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();
})
));
I tried to move the spy deceleration in beforeEach but still its giving the same error.
how to fix this error?
Thanks!
More From » angular