How to Mock Axios with Jest

Growing green plants on soil
Reading Time: < 1 minutes

Axios is a popular JavaScript library used for making HTTP requests in web applications. Jest, on the other hand, is a JavaScript testing framework that comes with a built-in mocking feature that makes it easy to mock Axios in your tests. In this blog post, we’ll explore how to mock Axios with Jest, step by step.


To mock Axios with Jest, you can use the Jest mock function to replace the actual Axios library with a mock implementation.

Here is an example of how to mock Axios with Jest:

// Import the Axios library
import axios from 'axios';

// Mock the Axios library with Jest
jest.mock('axios');

// Define the mock response data
const mockResponse = {
  data: {
    id: 1,
    name: 'John Doe',
  },
};

// Set up the mock implementation for Axios
axios.get.mockImplementation(() => Promise.resolve(mockResponse));

// Call the Axios method in your test
axios.get('/users/1').then((response) => {
  expect(response.data).toEqual(mockResponse.data);
});

In the example above, we first import the Axios library and then mock it with Jest. We then define a mock response data object and set up the mock implementation for the Axios get method to return a Promise that resolves with the mock response data.

Finally, we call the Axios get method in our test and use Jest’s expect function to assert that the response data matches the mock response data.

Note that you may need to modify this example to suit your specific use case, depending on the methods you are calling and the data you are expecting in response.

,

About the author

Andrés Canavesi
Andrés Canavesi

Software Engineer with 15+ experience in software development, specialized in Salesforce, Java and Node.js.


Related posts


2 responses to “How to Mock Axios with Jest”

  1. your line of code axios.get.mockImplementation(() => Promise.resolve(mockResponse));

    won’t work without this line:

    axios.get as jest.MockedFunction;

    because jest.mock(“axios”) just gives you jest.fn(), it doesnt have the “get” function.

Leave a Reply

%d bloggers like this: