I'm testing an Angular 4 component with a function that makes a HTTP request (returning an observable) and then calls another function in the observables subscribe method. I want to test that the function in the subscribe is being called correctly. The component looks like this:
logIn(): void {
this.loginService.logIn(user)
.subscribe(() => {
this.router.navigateByUrl('/')
})
}
I've mocked the service in the component's spec:
loginServiceStub = {
logIn(user: User) {
return Observable.of(true)
},
}
And I've attached a spy to the router and the login service to know if they have been called:
const logInSpy = spyOn(loginService, 'logIn')
const navigateByUrlSpy = spyOn(router, 'navigateByUrl')
When calling the components login method, the logInSpy is being called but the navigateByUrlSpy is not and the subscribe method is not being run. How should I set up the mock logIn to get this working?
Try the following
Stub:
loginServiceStub = {
logIn: jasmine.createSpy('logIn').and.returnValue(Observable.of(true))
}
In the test:
const navigateByUrlSpy = spyOn(router, 'navigateByUrl').and.callThrough();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With