JavaScript API Mocking Techniques

API mocking has become an integral part of the software development process, especially in JavaScript development. It allows developers to simulate actual APIs and receive realistic responses generated with custom data. This practice proves invaluable in various scenarios, such as writing unit tests or dealing with situations where external dependencies are unavailable. 

What is API Mocking? 

API mocking involves creating a simulation or imitation of an API’s behavior without actually invoking the real API. Developers use this technique to emulate the responses that their applications would receive from a live API, enabling efficient testing and development. 

Why Do We Need API Mocking? 

Testing Scenarios: When writing unit tests, developers need to isolate the code they are testing from external dependencies. Mocking APIs helps in creating controlled environments for testing specific scenarios. 

Dependency Unavailability: In situations where the actual API is not accessible—perhaps it’s under development, or there are restrictions—mocking allows developers to continue working on their code by simulating the expected API responses. 

Performance Testing: Developers can use API mocking to simulate different performance scenarios, ensuring their applications can handle various response times and loads. 

Step 1—Installing JSON Server 

The first step is to install the JSON Server globally. Then, you can use it for any project when needed.


npm install -g json-server

Step 2—Creating the mock data file

Then, create a JSON file with the necessary mock data. 


"users": [ 
{"id":"1","name": "Nishani", "usertype": "Admin"}, 
{"id":"2","name": "Nishani", "usertype": "Manager"}, 
{"id":"3","name": "Nishara", "usertype": "Admin"}, 
{"id":"4","name": "Nimal", "usertype": "Manager"}, 
{"id":"5","name": "Nilantha", "usertype": "Manager"} 

Step 3—Starting the Server 

After that, start the server with the following command.

json-server --watch users.json --port 8000 

Step 4—Using in the application 

JSON Server supports all GET, POST, PUT, PATCH,and DELETE request methods. The following code shows how to use the JSON Server for CRUD operations in a React application. 

import http from "../http-common"; 
import axios from "axios"; 
export default axios.create({ 
baseURL: "http://localhost:8000", 
headers: { 
"Content-type": "application/json" 
export const getAllUsers = () => { 
return http.get("/users"); 
export const getUser = (id) => { 
return http.get(/users/${id} ); 
export const createUser = (data) => { 
return"/users", data); 
export const updateUsers = (id, data) => { 
return http.put(/users/${id} , data); 
export const removeUser = (id) => { 
return http.delete(/users/${id} ); 

Different API Mocking Techniques in JavaScript:- 

  1. Manual Mocks:- 

This technique involves manually creating mock objects or functions that mimic the behavior of the real API. While it provides full control over the mock, it can be time-consuming and may not scale well for complex APIs.

// Manual mock example

const mockApiResponse = { 
data: 'Mocked response', 
const myApi = { 
fetchData: () => Promise.resolve(mockApiResponse), 
// Usage in code 
myApi.fetchData().then(response => { 
console.log(; // Outputs: 'Mocked response' 
  1. Nock:- 

Nock is a popular JavaScript library for HTTP mocking. It intercepts outgoing requests and allows developers to define custom responses. It is particularly useful for testing scenarios where specific HTTP requests need to be mocked.

const nock = require(‘nock’); 

// Nock example

.reply(200, { data: 'Mocked response' }); 
// Usage in code 
.then(response => response.json()) 
.then(data => console.log(data)); // Outputs: { data: 'Mocked response' }
  1. Mock Service Worker (MSW):- 

MSW is a powerful library that intercepts requests on the network level, enabling realistic mocking for both client-side and server-side applications. It seamlessly integrates with popular testing libraries like Jest and testing-library/react. 

// MSW example 

import { setupWorker, rest } from 'msw'; 
const worker = setupWorker( 
rest.get('', (req, res, ctx) => { 
return res(ctx.json({ data: 'Mocked response' })); 
// Start the worker 
// Usage in code 
.then(response => response.json()) 
.then(data => console.log(data)); // Outputs: { data: 'Mocked response' }

Axios-mock-adapter for API Mocking

The Axios-mock-adapter is an NPM library that allows mocking API requests. It is pretty helpful in testing and fron-tend development as this library will enable us to send HTTP requests to an API. 

Step 1—Install the library 

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

Step 2—Create and pass an Axios instance to Axios adapter 

The following code creates an Axios instance and then passes it to the Axios adapter. 

import axios, { AxiosRequestConfig } from 'axios'; 
import AxiosMockAdapter from 'axios-mock-adapter'; 
const axiosMockInstance = axios.create(); 
const axiosLiveInstance = axios.create(); 
export const axiosMockAdapterInstance= new AxiosMockAdapter( 
{ delayResponse: 0 } 
export default process.env.isAxioMock? axiosMockInstance : axiosLiveInstance;

Step 3—Create the mock file

import { axiosMockAdapterInstance } from 'src/lib/axios'; 
.reply(() => { 
const profile: User = { 
id: 'u001', 
title: 'Manager', 
name: 'John Mayor', 
email: '' 
return [200, { User }];





Leave a Reply