如何使用带有Jest的toThrow断言引发Error的异步方法 [英] How to assert an async method throwing Error using toThrow with Jest

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

问题描述

我看过这个问题,期望得到一个Promise上班.在我的情况下,Error抛出在Promise之前和之外.

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+ .

因此,这仅在您使用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抛出的 > .

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

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

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