How to mock axios instance in jest

How to mock axios instance in Jest

In order to mock an axios instance in Jest, we can use the “jest.mock” function to mock the axios module and provide a custom implementation of the methods. This allows us to control the behavior and responses of the axios requests during testing.

Here’s an example of how to mock an axios instance in a Jest test:


    // Import the axios instance
    import axios from 'axios';

    // Import the module that contains the logic to test
    import SomeModule from './SomeModule';

    // Mock the axios module
    jest.mock('axios');

    // Create a custom implementation of the axios methods
    axios.get.mockImplementation((url) => {
      if (url === '/api/data') {
        // Return a mock response object
        return Promise.resolve({ data: { foo: 'bar' } });
      }
      // Default behavior if URL is not recognized
      return Promise.reject(new Error('Not Found'));
    });

    // Test the module that uses the axios instance
    describe('SomeModule', () => {
      test('should fetch data from the API', async () => {
        const result = await SomeModule.getData();
        expect(result).toEqual({ foo: 'bar' });
      });
    });
  

In this example, we first import the axios instance and the module we want to test (SomeModule). Then, we use “jest.mock” to mock the axios module. After that, we create a custom implementation of the axios.get method using “axios.get.mockImplementation”. In this implementation, we check the URL being requested and return a mock response accordingly. Finally, we test the SomeModule.getData() method and assert that it returns the expected result.

By mocking the axios instance, we can simulate different response scenarios and control the behavior of the API requests during testing. This allows for more thorough and reliable testing of modules that rely on axios for making API calls.

Leave a comment