Skip to content
Advertisement

Mock an axios 404 with Jest?

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?

Advertisement

Answer

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);
});
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement