lundi 12 février 2018

How to test catch blocks with Jest

I'm trying to test that when the libraryBlackBox rejects a promise, output is called with the string fail.

I can't figure out a nice way to test this without flushing the promises with a mixture of setTimeout() and done().

The following test snippet passes:

//  @flow
const libraryBlackBox = (bool: boolean) =>
  new Promise((res, rej) => (bool === true ? res(bool) : rej(bool)));

const output = jest.fn();

const testMe = (bool: boolean) =>
  libraryBlackBox(bool)
    .then(() => output('win'))
    .catch(() => output('fail'));

test('When testMe is called with false, output will be called with fail', done => {
  testMe(false);
  
  setTimeout(() => {
    expect.assertions(1);
    expect(output).toHaveBeenCalledWith('fail');
    done();
  }, 0);
});

What would be a more elegant solution to test this case?

Aucun commentaire:

Enregistrer un commentaire