UnhandledPromiseRejection警告: [英] UnhandledPromiseRejectionWarning:

查看:3683
本文介绍了UnhandledPromiseRejection警告:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试ReactJs组件,其中的一个组件具有一种可以获取数据的方法,而其中的获取具有应有的承诺.因此,我尝试创建一个模拟文件:

I'm trying to test ReactJs components, where one of them has a method in which it fetches data, the fetch has a promise in it.. So I tried to create a mock file:

  const apiFetch = {
      value() {
        return 42
      },
    }

module.exports = apiFetch

然后:

const spy = jest.spyOn(apiFetch, 'value')

const isValue = apiFetch.value()

expect(spy).toHaveBeenCalled()

expect(isValue).toBe(42)

测试通过,但是此警告仍在显示.

The test is passing, but this warning is still showing.

我又添加了一件事:

process.on('UnhandledPromiseRejectionWarning', (e) => { throw e })

UnhandledPromiseRejectionWarning:未处理的承诺拒绝.这 由抛出异步函数引起的错误 没有障碍,或者拒绝了没有处理的承诺 使用.catch(). (拒绝ID:188)

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 188)

推荐答案

在运行异步测试时,请记住,完成测试时需要指明测试方法.

When running async tests you should keep in mind that you need to indicate the test method when it has finished.

开玩笑,您可以执行以下操作:

With jest you can do something like:

apiFetch.js

apiFetch.js

const apiFetch = {
    value() {
        return Promise.resolve(42);
    },
}

module.exports = apiFetch

apiFetch.test.js:

apiFetch.test.js:

const apiFetch = require('./apiFetch');

test('the data is peanut butter', done => {
    apiFetch.value().then(data => {
        expect(data).toBe(42);
        done();
    })
});

done是一个插入的函数参数(由jest框架提供),在调用时表示测试方法的结束.

done is an injected function parameter (provided by the jest framework) that when called, indicates the end of the test method.

如果您在不使用jest(或mocha)的异步功能的情况下测试异步逻辑,那么即使异步承诺失败,测试也会通过

If you're testing async logic without using the async features of jest (or mocha) then tests will pass even though the async promises fail

修改

每个框架都有希望的支持.开玩笑的是这样的

Each framework has promise support. With jest it is something like

it('works with resolves', () => {
   expect.assertions(1);
   return expect(apiFetch.value()).resolves.toEqual(42);
});

使用纯回调时,请使用注入的完成.

When working with pure callbacks, use the injected done.

使用诺言时,可以使用注入的完成"功能,但是如果诺言失败并且未调用完成",则测试将在超时时失败.出于笑话,建议在测试承诺逻辑时使用'it','expect'和'resolve'.

When working with promises you could use the injected 'done' function, but if the promise fails and 'done' is not called, then the test will fail on timeout. With jest it is recommended to work with 'it' , 'expect' and 'resolve' when testing promise logic.

这篇关于UnhandledPromiseRejection警告:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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