如何使捕获的承诺在开玩笑中失败 [英] How to make catched promises fail in jest

查看:106
本文介绍了如何使捕获的承诺在开玩笑中失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个功能:

aPromise = require('axios');    
function middleware(callback) {
  axios.get('/api/get')
    .then(callback)
    .catch(callback);
}

考虑这个测试:

const callback = (err) => {
  expect(isError(err)).toBe(true);
  done();
};

middleware(callback);

isError 是一个lodash功能。

The isError is a lodash function.

考虑 aPromise 作为我想要测试的东西。如果承诺总是解决,那么这个测试不应该通过。但它会!那是因为承诺的捕获实际上捕获了期望异常。

Consider aPromise as something I want to test. If the promise always resolves, this test should not pass. But it will! And that's because the promise's catch actually catches the expect exception.

我的问题是:如何捕获错误在承诺的 catch 处理程序时 expect 在promise的中抛出错误然后 handler?

My question is: How to not catch the error in a promise's catch handler when expect throws an error in the promise's then handler?

请注意,我不使用async / await。

Note that I don't use async/await.

推荐答案

您需要创建失败的承诺,并且需要在测试中返回承诺。请查看测试承诺的文档

You need to create a failed promise and you need to return the promise in your test. Please have a look on the doc on testing promises.

aPromise = require('axios');    
jest.mock('axios', () => {
  get: ()=> jest.fn() //initialy mock the get function
})

it('catch failing promises',() = > {
    const result  = Promise.reject('someError'); //create a rejected promises
    aPromise.get.mockImplementation(() => result)// let `get` return the rejected promise
    const callback = jest.fn()
    middleware(callback)

    return result
        .then (()=>{
          expect(callback).toHaveBeenCalledWith('someError');
        })

})

这篇关于如何使捕获的承诺在开玩笑中失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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