【问题标题】:How can I check the type of the error thrown asyncronously in Jest?如何检查 Jest 中异步抛出的错误类型?
【发布时间】:2018-07-12 20:17:41
【问题描述】:

假设我有这样的功能:

const f = async () => {
  throw new Error('Huh???!');
};

我想测试它是否使用 Jest 抛出 RangeError(而不仅仅是 Error)。

test('f throws a RangeError', () => {
  expect(f()).rejects.toThrowError(RangeError);
});

但是这个测试通过了。

如何检查 Jest 中异步抛出的错误类型?

【问题讨论】:

  • 我不知道我是否正确,但您可以尝试在 try/catch 中 await f() 并在 catch 中检查 typeof 错误。
  • 这是一种选择,但rejects 是为了做awaiting
  • 那不是async

标签: javascript async-await jestjs


【解决方案1】:

你可以在rejects之后使用toBeInstanceOf匹配器:

test('f throws a RangeError', () => {
  expect(f()).rejects.toBeInstanceOf(RangeError);
});

【讨论】:

    猜你喜欢
    • 2018-02-13
    • 2020-10-21
    • 1970-01-01
    • 2019-07-01
    • 1970-01-01
    • 2019-07-05
    • 2016-11-13
    • 1970-01-01
    相关资源
    最近更新 更多