Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
807 views
in Technique[技术] by (71.8m points)

javascript - 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 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Edit:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...