How to make catched promises fail in jest

佐手、 提交于 2019-12-11 06:49:39

问题


Consider this function:

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

Consider this test:

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

middleware(callback);

The isError is a lodash function.

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.

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?

Note that I don't use async/await.


回答1:


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');
        })

})


来源:https://stackoverflow.com/questions/40402024/how-to-make-catched-promises-fail-in-jest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!