如何使用Jest测试catch块

时间:2018-02-12 17:52:38

标签: javascript testing jestjs

我正在尝试测试当libraryBlackBox拒绝承诺时,使用字符串output调用fail

我无法找到一种很好的方法来测试这个,而不会使用setTimeout()done()的混合来刷新承诺。

以下测试代码段通过:

//  @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);
});

测试此案例的更优雅的解决方案是什么?

0 个答案:

没有答案