如何使用 toThrow 和 Jest 断言抛出错误的异步方法 [英] How to assert an async method throwing Error using toThrow with Jest

查看:66
本文介绍了如何使用 toThrow 和 Jest 断言抛出错误的异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了这个问题,它期望一个 <代码>承诺工作.在我的情况下,ErrorPromise 之前和之外被抛出.

I have seen this question which expects a Promise to work. In my case the Error is thrown before and outside a Promise.

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

How can I assert the error in this case? I have tried the options below.

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

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

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

推荐答案

调用 throwThis 返回一个 Promise 应该用 Error 拒绝,所以语法应该是:

Calling throwThis returns a Promise that should reject with an Error so the syntax should be:

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

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

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

请注意,toThrow 已针对 PR 4884仅适用于 21.3.0+.

Note that toThrow was fixed for promises in PR 4884 and only works in 21.3.0+.

所以这仅在您使用 Jest 22.0.0 或更高版本时有效.

So this will only work if you are using Jest version 22.0.0 or higher.

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

If you are using an earlier version of Jest you can pass a spy to 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
});

...并可选择检查抛出的 Error 通过检查 spy.mock.calls[0][0].

...and optionally check the Error thrown by checking spy.mock.calls[0][0].

这篇关于如何使用 toThrow 和 Jest 断言抛出错误的异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆