如何使用带有Jest的toThrow断言引发Error的异步方法

时间:2019-02-07 18:52:45

标签: javascript testing jestjs

我已经看到this question期望Promise可以工作。在我的情况下,将Error放在Promise之前和之外。

在这种情况下如何断言错误?我已经尝试过以下选项。

test('Method should throw Error', async () => {

    let throwThis = async () => {
        throw new Error();
    };

    await expect(throwThis).toThrow(Error);
    await expect(throwThis).rejects.toThrow(Error);
});

1 个答案:

答案 0 :(得分:3)

调用throwThis返回一个Promise,应以Error拒绝,因此语法应为:

test('Method should throw Error', async () => {

  let throwThis = async () => {
    throw new Error();
  };

  await expect(throwThis()).rejects.toThrow(Error);  // SUCCESS
});

请注意,toThrow是针对PR 4884only works in 21.3.0+中的承诺而固定的。

所以这仅在您使用Jest 22.0.0或更高版本的情况下有效


如果您使用的是Jest的早期版本,则可以将spy传递给catch

test('Method should throw Error', async () => {

  let throwThis = async () => {
    throw new Error();
  };

  const spy = jest.fn();
  await throwThis().catch(spy);
  expect(spy).toHaveBeenCalled();  // SUCCESS
});

...,并可以选择检查抛出的by checking spy.mock.calls[0][0] Error

相关问题