When using Jest for unit testing, mocking Axios requests is a common requirement because we typically do not want to execute real HTTP requests during tests. Mocking enables us to simulate the response data for requests and ensures that our tests can run without network connectivity. Here are the steps to mock Axios requests in Jest:
-
Installing a Mocking Library (Optional): While Jest provides built-in mocking capabilities, we can use libraries such as
jest-mock-axiosto streamline the process. -
Creating a Mock: Within the test file, we can call
jest.mock('axios')to automatically mock the entire axios module. This intercepts all axios calls made during the test. -
Defining the Mock Implementation: Next, we can define a mock implementation where the code returns the specified data when attempting to send an HTTP request.
-
Running the Test: During the test, we verify that the code correctly processes the mock response.
-
Verifying Mock Invocation: Finally, we can confirm that the mock axios methods (e.g.,
getorpost) are called correctly with the appropriate parameters.
Here is an example:
javascript// Import the method to test and axios import { fetchData } from './fetchData'; import axios from 'axios'; // Mock the entire axios module at the top level scope jest.mock('axios'); describe('fetchData', () => { it('should return data when fetchData is called', async () => { // Set the data returned when axios.get is called const mockedResponse = { data: { items: ['item1', 'item2'] } }; axios.get.mockResolvedValue(mockedResponse); // Call the method to test const result = await fetchData(); // Check if the expected data is returned expect(result).toEqual(mockedResponse.data.items); // Verify that axios.get is called exactly once with the correct URL expect(axios.get).toHaveBeenCalledTimes(1); expect(axios.get).toHaveBeenCalledWith('expected-url'); }); });
In the above code example, we mock the axios.get request called internally by the fetchData function and set the data returned when it is invoked. Then, we run a test to verify that fetchData returns the data we set in the mock, as well as confirming that axios.get is correctly called.
This allows us to test our asynchronous code for correctly handling HTTP responses without relying on actual network requests.