Search code examples
rxjsobservablejestjs

Testing Observables with jest


How can I test Observables with Jest?

I have an Observable that fires ~every second, and I want to test that the 1st event is correctly fired, before jest times out.

const myObservable = timer(0, 1000); // Example here

it('should fire', () => {
  const event = myObservable.subscribe(data => {
    expect(data).toBe(0);
  });
});

This test passes, but it also passes if I replace with toBe('anything'), so I guess I am doing something wrong.

I tried using expect.assertions(1), but it seems to be only working with Promises.


Solution

  • There are some good examples in the Jest documentation about passing in an argument for the test. This argument can be called to signal a passing test or you can call fail on it to fail the test, or it can timeout and fail.

    https://jestjs.io/docs/en/asynchronous.html

    https://alligator.io/testing/asynchronous-testing-jest/

    Examples

    Notice I set the timeout to 1500ms

    const myObservable = timer(0, 1000); // Example here
    
    it('should fire', done => {
      myObservable.subscribe(data => {
        done();
      });
    }, 1500); // Give 1500ms until it fails
    

    Another way to see if it fails using setTimeout

    const myObservable = timer(0, 1000); // Example here
    
    it('should fire', done => {
      myObservable.subscribe(data => {
        done();
      });
    
      // Fail after 1500ms
      setTimeout(() => { done.fail(); }, 1500);
    }, timeToFail);