Geraint Anderson
Geraint Anderson

Reputation: 3383

Spy on a function that returns an observable

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?

Upvotes: 6

Views: 17408

Answers (1)

Sonicd300
Sonicd300

Reputation: 2049

Try the following

Stub:

loginServiceStub = {
  logIn: jasmine.createSpy('logIn').and.returnValue(Observable.of(true))
}

In the test:

const navigateByUrlSpy = spyOn(router, 'navigateByUrl').and.callThrough();

Upvotes: 14

Related Questions