问题
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