Rxjs: [support] Spying on `observableThrowError` - unit testing

Created on 4 Oct 2018  路  1Comment  路  Source: ReactiveX/rxjs

Previously in _RxJS_ 5 in our file: service.ts we had:

import { Observable } from 'rxjs/Observable';

// in our method we had:
return Observable.throw({ error: 'lol' });

Using _Jasmine_ it was tested service.spec.ts thus:

spyOn(Observable, 'throw');

// in the test
expect(Observable.throw).toHaveBeenCalledWith({error: 'lol'});

Now with _RxJS_ 6 our file service.ts has:

import { throwError as observableThrowError } from 'rxjs';

// in our method we have:
return observableThrowError({ error: 'lol' });

But how do you spy on throwError or observableThrowError? 馃槚

Most helpful comment

Obviously I can't see all of your code in context there, but I believe it would be better to test that the Observable your service returns throws, rather than testing that the throw method was called. It seems like you're testing an (RxJS v5 dependent) implementation detail of your service rather than the actual result you want from your service?

So the jasmine test that does what you want it to under RxJS 6 (and also works under v5) would look something like

it('should throw an error', (done: DoneFn) => {
  serviceUnderTest.methodThatReturnsThrowingObs().subscribe({
    error: (err) => {
      expect(err).toEqual({ error: 'lol' });
      done();
    }
  })
});

(didn't write that code in an editor, may contain typos!)

Also, while I'm not a maintainer here, I believe that somewhere like Stack Overflow is a better place 'how to' for queries like this (mainly in that you are likely to get more eyes on the problem and a faster answer).

>All comments

Obviously I can't see all of your code in context there, but I believe it would be better to test that the Observable your service returns throws, rather than testing that the throw method was called. It seems like you're testing an (RxJS v5 dependent) implementation detail of your service rather than the actual result you want from your service?

So the jasmine test that does what you want it to under RxJS 6 (and also works under v5) would look something like

it('should throw an error', (done: DoneFn) => {
  serviceUnderTest.methodThatReturnsThrowingObs().subscribe({
    error: (err) => {
      expect(err).toEqual({ error: 'lol' });
      done();
    }
  })
});

(didn't write that code in an editor, may contain typos!)

Also, while I'm not a maintainer here, I believe that somewhere like Stack Overflow is a better place 'how to' for queries like this (mainly in that you are likely to get more eyes on the problem and a faster answer).

Was this page helpful?
0 / 5 - 0 ratings