Testing the Observer complete event with Jest?

Viewed 1156

The RxJS Observer fires the events:

  • complete
  • error
  • next

If we want to test for the complete event with Jest. How is this done?

For example we can test the next and error events, because those functions pass data:

o.subscribe(result => {
  expect(result.data.length).toEqual(1);
}, 
(e)=>{expect(e).toBeFalsy()}, 
()=>{ WHAT TO EXPECT HERE? }

The complete event does not. The function signature is ()=>void. How do we test that function signature?

Also the line (e)=>{expect(e).toBeFalsy()} because it never actually fires. Is there a way to check that a callback does not run?

2 Answers
const toPromise = obs =>
  new Promise((complete, error) => {
    obs.subscribe({ complete, error });
  });

import { getUserEvents } as user from '../user';

// The assertion for a promise must be returned.
it('works with promises', () =>
  expect(toPromise(getUserEvents(4))).resolves.toEqual('Mark'))

Via:

Furthermore, since Jest will fail on Errors being thrown, you can use any testing framework inside of its test. E.g. import 'rxjs/testing', like described here

How to test that the error callback is not called is here.

Looks like this will test the complete callback:

let complete = false;
let completeHandler = ()=>{
  complete = true;
  expect(complete).toBeTruthy()
};
let errorHandler = (e)=>{
  console.log("THIS IS NEVER EXECUTED");
  console.log("HOW DO WE VERIFY THAT IT IS NOT?");
let o:Observable<Result> = fn(data, errorHandler, completeHandler);
o.subscribe();

The errorHandler and completeHandler are baked into the Observable<Result returned by the fn function.

Related