How to mock interceptors when using jest.mock('axios')?

前端 未结 2 1966
深忆病人
深忆病人 2021-01-01 07:17

When running a test using jest I have the basic test suit syntax:

jest.mock(\'axios\');

describe(\'app\', () => {
    let render

    beforeEach(() =>         


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

    Make sure to mock out the interceptors and axios.create if used:

    // Replace any instances with the mocked instance (a new mock could be used here instead):
    axios.create.mockImplementation((config) => axios);
    
    // Mock out the interceptor (assuming there is only one):
    let requestCallback = () => {
      console.log("There were no interceptors");
    };
    axios.interceptors.request.use.mockImplementation((callback) => {
      requestCallback = callback;
    });
    
    // Mock out the get request so that it returns the mocked data but also calls the 
    // interceptor code:
    axios.get.mockImplementation(() => {
      requestCallback();
      return {
        data: "this is some data"
      };
    });
    

    Note if this doesn't work:

    This example assumes that the create and interceptor calls are in a place where Jest can mock them out. Placing the axios.create or axiosInstance.interceptors.request.use lines outside the scope of the function may cause the above mocking to fail. This is an example file where Jest can mock them out:

    const axios = require('axios');
    
    const DEBUG = true;
    
    const customRequest = (url) => {
      // Example of axios.create from https://www.npmjs.com/package/axios#axioscreateconfig
      const axiosInstance = axios.create({
        baseURL: 'https://some-domain.com/api/',
        timeout: 1000,
        headers: {'X-Custom-Header': 'foobar'}
      });
    
      // Example of interceptor taken from https://stackoverflow.com/a/52737325/7470360:
      axiosInstance.interceptors.request.use((config) => {
        if (DEBUG) { console.info("Request called", config); }
        return config;
      }, (error) => {
        if (DEBUG) { console.error("Request error ", error); }
        return Promise.reject(error);
      });
    
      return axiosInstance.get(url);
    }
    
    module.exports = customRequest;
    

    The mocking code will mock out the axios.create call and the axiosInstance calls in customRequest. Moving either the creation or interception outside the function will cause the mocks to fail.

    0 讨论(0)
  • 2021-01-01 07:44

    This was enough in the end

    jest.mock('axios', () => {
        return {
            interceptors: {
                request: { use: jest.fn(), eject: jest.fn() },
                response: { use: jest.fn(), eject: jest.fn() },
            },
        };
    });
    
    0 讨论(0)
提交回复
热议问题