How to mock axios.create([config]) function to return its instance methods instead of overriding them with mock?

纵饮孤独 提交于 2020-04-12 07:47:08

问题


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 result of the get, post method properly.

This is how the code looks like in the actual file:

 export const axiosInstance = axios.create({
        headers: {
           ...headers
        },
        transformRequest: [
            function (data, headers) {
                return data;
            },
        ],
    });
    const response = await axiosInstance.get(endpoint);

And here is the mock setup for axios inside the test file

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

How could I get all of the instance methods in the axiosInstance variable instead of just having a mock function which does nothing?

Documentation for axios.create and instance methods: https://github.com/axios/axios#instance-methods


回答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();

export default axios;
working example


回答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.



来源:https://stackoverflow.com/questions/60428640/how-to-mock-axios-createconfig-function-to-return-its-instance-methods-inste

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!