✅ How to Mock Axios with Jest: A Senior Developer’s Guide

When writing unit tests for JavaScript or TypeScript applications, mocking HTTP requests is crucial to ensure your tests are fast, reliable, and independent of external services. One of the most commonly used libraries for making HTTP calls is axios, and if you're using Jest, mocking it is easier than you think.

In this post, I’ll walk you through how to mock axios in Jest, share best practices, and explain a few gotchas to watch out for—because nobody likes flaky tests (except maybe that one intern, but we’ve sent them for coffee ☕).


🚀 Why Mock Axios?

Before we dive into the code, here’s why you should mock axios:

  • ✅ Avoid hitting real APIs during tests
  • ✅ Improve test performance and isolation
  • ✅ Control response data for various test scenarios
  • ✅ Simulate edge cases like timeouts, errors, or empty data

🛠️ Setting Up Your Project

Make sure you have axios and jest installed:

npm install axios
npm install --save-dev jest

If you're using TypeScript:

npm install --save-dev @types/jest ts-jest

📦 Example Code to Test

Let’s say we have a file userService.js:

// userService.js
import axios from 'axios';

export async function getUser(id) {
  const response = await axios.get(`/api/users/${id}`);
  return response.data;
}

🧪 Jest Test with Axios Mock

Now let’s write a unit test and mock axios.

// userService.test.js
import axios from 'axios';
import { getUser } from './userService';

jest.mock('axios');

describe('getUser', () => {
  it('should fetch user data', async () => {
    const mockData = { id: 1, name: 'Alice' };
    axios.get.mockResolvedValue({ data: mockData });

    const result = await getUser(1);

    expect(result).toEqual(mockData);
    expect(axios.get).toHaveBeenCalledWith('/api/users/1');
  });

  it('should handle API errors', async () => {
    axios.get.mockRejectedValue(new Error('API down'));

    await expect(getUser(1)).rejects.toThrow('API down');
  });
});

🧠 Pro Tips for Mocking Axios

  • Use mockResolvedValue and mockRejectedValue for Promises.
  • Don’t forget to reset mocks between tests with jest.resetAllMocks() if needed.
  • Mock only what you need: If you're only using axios.get, no need to mock the entire library.
  • Prefer integration tests for full end-to-end API interactions—save mocks for unit tests.

🧼 Cleaning Up with BeforeEach

If you're mocking axios in multiple tests:

beforeEach(() => {
  jest.clearAllMocks();
});

🔄 Using Axios Mock Adapter (Alternative)

If you need more fine-grained control, consider using axios-mock-adapter. But for most Jest unit tests, the built-in mocking is sufficient.


🧾 Final Thoughts

Mocking axios with Jest is straightforward and helps keep your unit tests fast, reliable, and predictable. As a senior developer, I recommend keeping your tests tight, focused, and mocking only what you truly need.

Remember: Test behavior, not implementation.

If this helped you, share it with your team or that dev who still logs console.log("test") instead of writing actual tests. 😉