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
JavaScript
x
18
18
1
const mockAccountEnquiry = () => {
2
axios.post.mockImplementation(async (url, testParams) => {
3
if (url === 'https://blah/v1/payIDEnquiry') {
4
if (testParams.payID === 'not-found') {
5
jest.fn().mockReturnValue(Promise.reject(Error('error')));
6
}
7
return {
8
status: 200,
9
data: {
10
AccountStatus: {
11
nppReachable: testParams.nppReachable,
12
},
13
},
14
};
15
}
16
});
17
};
18
Create a test case
JavaScript
1
7
1
it('Failed request', async() => {
2
mockAccountEnquiry();
3
const response = await backend.handler(testData);
4
expect(axios.post.mock.calls[0][0]).toBe(enquiryUrl);
5
});
6
7
How to mock the 404 request?
Advertisement
Answer
Using https://www.npmjs.com/package/axios-mock-adapter will make mocking API very simple.
JavaScript
1
12
12
1
var axios = require("axios");
2
var MockAdapter = require("axios-mock-adapter");
3
4
var mock = new MockAdapter(axios);
5
6
mock.onPost(enquiryUrl).reply(404);
7
8
it('Failed request', async() => {
9
const response = await backend.handler(testData);
10
expect(mock.history.post[0].url).toBe(enquiryUrl);
11
});
12