Skip to content Skip to sidebar Skip to footer

How To Mock Axios.create([config]) Function To Return Its Instance Methods Instead Of Overriding Them With Mock?

I'm trying to mock axios.create() because I'm using its instance across the app and obviously need all of its implementation which is destroyed by the mock, thus cannot get the res

Solution 1:

You can use jest's genMockFromModule. It will generate jest.fn() for each of the modules's methods and you'll be able to use .mockReturnThis() on create to return the same instance.

example:

./src/__mocks__/axios.js
const axios = jest.genMockFromModule('axios');

axios.create.mockReturnThis();

exportdefault axios;
working example

Edit:

from Jest 26.0.0+ it's renamed to jest.createMockFromModule

Solution 2:

Ended up sticking with the axios mock and just pointing to that mock by assigning the axiosInstance pointer to created axios mock. Basically as @jonrsharpe suggested

Briefly:

import * as m from'route';
jest.mock('axios', () => {
        return {
            create: jest.fn(),
            get: jest.fn(() =>Promise.resolve()),
        };
    }
);
m.axInstance = axios

Would be very nice though if I could have gone without it.

Solution 3:

The following code works!

jest.mock("axios", () => {
    return {
        create: jest.fn(() => axios),
        post: jest.fn(() =>Promise.resolve()),
    };
});

Post a Comment for "How To Mock Axios.create([config]) Function To Return Its Instance Methods Instead Of Overriding Them With Mock?"