When mocking a 404 error the result is
Uncaught UnhandledPromiseRejection: 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(). The promise rejected with the reason "Error: error".
Setup a basic Mock
const mockAccountEnquiry = () => {
axios.post.mockImplementation(async (url, testParams) => {
if (url === 'https://blah/v1/payIDEnquiry') {
if (testParams.payID === 'not-found') {
jest.fn().mockReturnValue(Promise.reject(Error('error')));
}
return {
status: 200,
data: {
AccountStatus: {
nppReachable: testParams.nppReachable,
},
},
};
}
});
};
Create a test case
it('Failed request', async() => {
mockAccountEnquiry();
const response = await backend.handler(testData);
expect(axios.post.mock.calls[0][0]).toBe(enquiryUrl);
});
How to mock the 404 request?
Using https://www.npmjs.com/package/axios-mock-adapter will make mocking API very simple.
var axios = require("axios");
var MockAdapter = require("axios-mock-adapter");
var mock = new MockAdapter(axios);
mock.onPost(enquiryUrl).reply(404);
it('Failed request', async() => {
const response = await backend.handler(testData);
expect(mock.history.post[0].url).toBe(enquiryUrl);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.