Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 551
Geraint Anderson Avatar asked Aug 23 '17 16:08

Geraint Anderson


1 Answers

Try the following

Stub:

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

In the test:

const navigateByUrlSpy = spyOn(router, 'navigateByUrl').and.callThrough();
like image 94
Sonicd300 Avatar answered Oct 16 '22 14:10

Sonicd300