How to make Mocking API Calls with Jest: A Complete Tutorial

Mocking API calls with Jest is essential for writing reliable, fast tests. Use its extensive library to control mocked responses and adapters for advanced cases.

Steven Ang Cheong Seng

Steven Ang Cheong Seng

26 July 2025

How to make Mocking API Calls with Jest: A Complete Tutorial

When writing tests for code that makes API calls, it's important to mock out those calls to ensure your tests are reliable, fast, and not dependent on an external service. Jest, a popular JavaScript testing framework, provides several ways to easily mock API calls in your tests. Let's dive into the different approaches you can use.

💡
You can mock APIs with any application, but you should consider using the best API platform called Apidog!

Apidog is a comprehensive low-code API platform that equips developers with high-quality functionalities for the entire API lifecycle. With additional tools like automated code generation, CI/CD integration, and customizable scripts, experience professional API development within a single platform!

To learn more about Apidog, make sure to click the button below!
Apidog An integrated platform for API design, debugging, development, mock, and testing
REAL API Design-first Development Platform. Design. Debug. Test. Document. Mock. Build APIs Faster & Together.

Using jest.mock()

One way to mock API calls in Jest is by using the jest.mock() function to mock the entire module that makes the API request. Here's an example:

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

export const getUsers = () => {
  return axios.get('/users');
};
// api.test.js
import axios from 'axios';
import { getUsers } from './api';

jest.mock('axios');

test('getUsers returns data from API', async () => {
  const users = [{ id: 1, name: 'John' }];
  axios.get.mockResolvedValueOnce({ data: users });
  
  const result = await getUsers();
  
  expect(axios.get).toHaveBeenCalledWith('/users');
  expect(result.data).toEqual(users);
});

In this example, we use jest.mock('axios') to automatically mock the entire axios module. Then we use axios.get.mockResolvedValueOnce() to mock the response for the next axios.get call. Our test can then verify the API was called correctly and returns the mocked data1.

Using Manual Mocks

Another approach is to manually mock the module that makes the API call by creating a __mocks__ folder and putting a mock implementation file inside:

// __mocks__/axios.js
export default {
  get: jest.fn(() => Promise.resolve({ data: {} })),
  post: jest.fn(() => Promise.resolve({ data: {} })),
  // ...
};

Now in your test, you can mock different responses for each test:

// api.test.js
import axios from 'axios';
import { getUsers } from './api';

jest.mock('axios');

test('getUsers returns data from API', async () => {
  const users = [{ id: 1, name: 'John' }];
  axios.get.mockResolvedValueOnce({ data: users });
  
  const result = await getUsers();
  
  expect(axios.get).toHaveBeenCalledWith('/users');
  expect(result.data).toEqual(users);
});

With this manual mock, you have full control to mock the different Axios methods like get, post, etc. with your own implementations2.

Using Axios-mock-adapter

You can use the library to mock Axios requests more advancedly. First, install it:

npm install axios-mock-adapter --save-dev

Then in your tests:

// api.test.js
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import { getUsers } from './api';

describe('getUsers', () => {
  let mock;
  
  beforeAll(() => {
    mock = new MockAdapter(axios);
  });
  
  afterEach(() => {  
    mock.reset();
  });
  
  test('returns users data', async () => {
    const users = [{ id: 1, name: 'John' }];
    mock.onGet('/users').reply(200, users);
    
    const result = await getUsers();
    
    expect(result.data).toEqual(users);  
  });
});

With the axios-mock-adapter, you can mock requests based on URLs, parameters, headers, and more. You can also simulate errors and timeouts.

Injecting a Mocked Axios Instance

If your code uses axios directly, another option is to inject a mocked axios instance into your code during tests:

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

export const getUsers = () => {
  return axios.get('/users');
};
// api.test.js
import axios from 'axios';
import { getUsers } from './api';

jest.mock('axios', () => ({
  get: jest.fn(),
}));

test('getUsers returns data from API', async () => {
  const users = [{ id: 1, name: 'John' }];
  axios.get.mockResolvedValueOnce({ data: users });
  
  const result = await getUsers();
  
  expect(axios.get).toHaveBeenCalledWith('/users');
  expect(result.data).toEqual(users);
});

Here we mock axios itself, not the entire module, and provide our own mocked get function.

Tips for Mocking API Calls

Here are a few tips to keep in mind when mocking API calls in Jest:

Mock APIs With Apidog

If you wish to try a different API development experience, you can consider using Apidog!

apidog interface
button

Apidog is a low-code API platform that provides developers with a simple and intuitive user interface for developing APIs. With Apidog, you can build, test, mock, and document APIs. Let us take a closer look at Apidog!

Apidog Smart Mock

apidog smart mock

Let Apidog automatically generate realistic mock data without manual configuration if you have no definitive mock rules.

Apidog Advanced Mock

apidog advanced mock
button

Modify API responses with custom scripts to simulate real-life interactions between the client and server side.

Apidog Cloud Mock

apidog cloud mock

Collaborate with your team with the cloud mock feature through a fixed address, accessible on the cloud mock server.

Conclusion

Mocking is a fundamental skill for writing good tests, especially when dealing with external dependencies like API calls. Jest provides many ways to mock API calls in your tests, from mocking entire modules with jest.mock(), to manually mocking modules, to using libraries like axios-mock-adapter for more advanced cases. The key is to choose the right approach for your needs while keeping your tests independent and focused on the code being tested, not the implementation details of the APIs. With these mocking techniques in your toolbelt, you can write resilient tests for code that depends on APIs.

Explore more

How to Use Wave – An Open-source Terminal

How to Use Wave – An Open-source Terminal

Wave Terminal is an open-source terminal that blends classic command-line power with modern graphical tools, file previews, web browsing, and AI assistance. This guide shows you how to install, customize, and master Wave Terminal.

13 August 2025

How to Use BlueJ - A Free Java Development Environment for Beginners

How to Use BlueJ - A Free Java Development Environment for Beginners

BlueJ is a free Java development environment that makes learning object-oriented programming simple and interactive. This guide shows you how to install, use, and master BlueJ's visual tools.

13 August 2025

How to Set an Enumeration for a Field (e.g. string, array, etc.) in Apidog

How to Set an Enumeration for a Field (e.g. string, array, etc.) in Apidog

Set Apidog enumerations for strings, arrays, and more with this guide. Learn to use AI, JSON Schema, and reusable models for clear, error-free API documentation and testing.

13 August 2025

Practice API Design-first in Apidog

Discover an easier way to build and use APIs