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

后端 未结 2 1185
迷失自我
迷失自我 2021-01-07 10:23

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

相关标签:
2条回答
  • 2021-01-07 10:50

    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
    0 讨论(0)
  • 2021-01-07 10:55

    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.

    0 讨论(0)
提交回复
热议问题