axios-mock-adapter vs fetch-mock vs mockttp vs nock
Strategic HTTP Mocking: Choosing the Right Tool for Frontend Architecture
axios-mock-adapterfetch-mockmockttpnockSimilar Packages:

Strategic HTTP Mocking: Choosing the Right Tool for Frontend Architecture

axios-mock-adapter, fetch-mock, mockttp, and nock are essential utilities for simulating network responses in JavaScript applications, enabling robust testing and isolated development. axios-mock-adapter is a dedicated solution for intercepting requests made specifically by the Axios library, offering a simple API for defining mock responses directly in test code. fetch-mock serves a similar purpose but targets the native fetch API (or node-fetch), allowing developers to mock browser-native networking without external dependencies. nock is a mature, Node.js-specific tool that intercepts HTTP requests at the low-level socket layer, making it ideal for testing backend integrations regardless of the high-level HTTP client used. mockttp stands out as a standalone mock server that runs independently, capable of handling requests from any client (browser, Node, mobile) and supporting complex scenarios like CORS, HTTPS, and traffic inspection.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
axios-mock-adapter03,54367.9 kB962 years agoMIT
fetch-mock01,309157 kB1110 months agoMIT
mockttp08821.98 MB403 days agoApache-2.0
nock013,129185 kB100a month agoMIT

Strategic HTTP Mocking: Choosing the Right Tool for Frontend Architecture

In modern frontend development, relying on live APIs during testing or local development is a recipe for flaky tests and slow workflows. We need reliable ways to simulate network responses. The JavaScript ecosystem offers four distinct approaches: axios-mock-adapter, fetch-mock, mockttp, and nock. While they all solve the same basic problem—returning fake data instead of hitting a real server—they operate at different layers of the network stack and serve different architectural needs.

Let's break down how they work, where they shine, and how to implement them in real scenarios.

🎯 Interception Layer: Library vs. Global vs. Socket vs. Server

The most critical difference is where these tools intercept your request. This dictates what kind of application code they can test.

axios-mock-adapter hooks directly into the Axios instance. It does not touch the network stack; it simply prevents Axios from sending the request and returns a promise immediately.

// axios-mock-adapter: Hooks into Axios instance
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';

const mock = new MockAdapter(axios);

mock.onGet('/api/users').reply(200, [{ id: 1, name: 'Alice' }]);

// Works only for requests made via this axios instance
const response = await axios.get('/api/users');

fetch-mock replaces the global fetch function. It intercepts calls before they leave the JavaScript runtime, making it suitable for code using native fetch or node-fetch.

// fetch-mock: Replaces global fetch
import fetchMock from 'fetch-mock';

fetchMock.get('/api/users', [{ id: 1, name: 'Alice' }]);

// Intercepts any call to global fetch()
const response = await fetch('/api/users');
const data = await response.json();

nock intercepts at the Node.js HTTP socket layer. It doesn't care if you use Axios, Fetch, or http.request; it stops the request before it leaves the Node process. This makes it powerful but limited to Node.js environments.

// nock: Intercepts at Node HTTP socket level
import nock from 'nock';
import axios from 'axios';

nock('http://api.example.com')
  .get('/users')
  .reply(200, [{ id: 1, name: 'Alice' }]);

// Works with ANY http client in Node
const response = await axios.get('http://api.example.com/users');

mockttp spins up a real, standalone HTTP server on your machine. Your application sends real network requests to this local server, which then returns your mocked responses. This is the most realistic simulation.

// mockttp: Runs a real local server
import mockttp from 'mockttp';

const mockServer = mockttp.getLocal();
await mockServer.start();
const url = mockServer.url;

await mockServer.forGet('/users').thenReply(200, JSON.stringify([{ id: 1, name: 'Alice' }]));

// Real network request to local server
const response = await fetch(`${url}/users`);

🌐 Environment Compatibility: Browser, Node, or Both?

Your testing environment often dictates your choice. Some tools simply cannot run in a browser.

  • axios-mock-adapter: Works in both Browser and Node, but only if you are using Axios.
  • fetch-mock: Works in both Browser and Node, provided you are using fetch.
  • nock: Node.js only. It relies on internal Node modules (http, https) that do not exist in browsers. Using it in a browser test suite will crash your tests.
  • mockttp: The server runs in Node, but it is designed to be tested by clients in any environment (Browser, Node, Mobile, Docker). You start the server in your test setup, then point your browser-based app to the server's URL.
// nock: Will FAIL in browser environments
// import nock from 'nock'; // Error: Module not found or internal Node APIs missing

// mockttp: Server runs in Node, client can be anywhere
// Test Setup (Node)
const server = await mockttp.start();
// Browser Code (running in Puppeteer/Playwright/Selenium)
// fetch('http://localhost:' + server.port + '/data') -> Works perfectly

⚙️ Advanced Scenarios: CORS, HTTPS, and Traffic Inspection

Simple 200 OK responses are easy. Real-world apps deal with Cross-Origin Resource Sharing (CORS), SSL certificates, and complex header validation. Here is where the tools diverge significantly.

Handling CORS Browsers block requests to different domains unless the server sends specific headers. axios-mock-adapter and fetch-mock often struggle here because they bypass the actual network layer where CORS checks happen. mockttp handles this naturally because it acts as a real server.

// axios-mock-adapter: Hard to simulate real CORS preflight
// You manually add headers, but the browser's actual CORS check is bypassed
mock.onAny().reply((config) => {
  return [200, {}, { 'Access-Control-Allow-Origin': '*' }];
});

// mockttp: Real CORS handling
// The browser sends an OPTIONS request, mockttp handles it, then the GET
await mockServer.forOptions('/users').thenReply(204);
await mockServer.forGet('/users').thenReply(200, jsonData, {
  headers: { 'Access-Control-Allow-Origin': 'https://my-app.com' }
});

HTTPS and SSL Testing secure endpoints requires valid certificates. nock and axios-mock-adapter typically mock the logic without establishing a real TLS handshake. mockttp can generate valid self-signed certificates on the fly, allowing you to test how your app handles SSL errors or client certificates.

// nock: Mocks HTTPS logically, no real TLS handshake
nock('https://secure-api.com').get('/data').reply(200, 'ok');

// mockttp: Real HTTPS server with generated certs
const httpsServer = await mockttp.start({ https: true });
// Client must trust the CA or disable rejection
await httpsServer.forGet('/data').thenReply(200, 'ok');

Inspecting Raw Traffic Sometimes you need to verify that a specific header was sent or that the request body matches an exact schema. nock is excellent for asserting request details in Node.

// nock: Asserts request details strictly
nock('http://api.com')
  .post('/login', { user: 'admin' }) // Verifies body
  .matchHeader('Authorization', 'Bearer token123') // Verifies header
  .reply(200, { success: true });

// mockttp: Inspects traffic after the fact
const endpoint = await mockServer.forPost('/login').thenReply(200);
await makeLoginRequest();
const requests = await endpoint.getSeenRequests();
console.log(requests[0].headers['authorization']); // Inspect raw headers

🧩 Integration Patterns: How They Fit in Your Tests

The way you integrate these tools affects your test maintenance and reliability.

Inline vs. External Setup axios-mock-adapter, fetch-mock, and nock are usually defined inline within your test file. This keeps the mock logic close to the test case but can clutter large test files.

// fetch-mock: Inline definition
it('loads user data', async () => {
  fetchMock.getOnce('/api/user', { name: 'John' });
  const user = await getUser();
  expect(user.name).toBe('John');
  fetchMock.restore();
});

mockttp requires a lifecycle setup. You start the server before tests and stop it after. This adds a bit of boilerplate but decouples the mock definition from the client code, allowing you to change mock rules dynamically during a test run.

// mockttp: Lifecycle setup
describe('User Flow', () => {
  let server;
  
  beforeEach(async () => {
    server = mockttp.getLocal();
    await server.start();
  });
  
  afterEach(async () => {
    await server.stop();
  });

  it('handles dynamic rules', async () => {
    await server.forGet('/status').thenReply(200, 'Up');
    // ... run test ...
    // Change rule mid-test for next scenario
    await server.forGet('/status').thenReply(500, 'Down');
  });
});

📊 Summary: Key Differences

Featureaxios-mock-adapterfetch-mocknockmockttp
TargetAxios onlyFetch APIAny Node HTTP clientAny Client (via Network)
EnvironmentBrowser & NodeBrowser & NodeNode OnlyServer: Node / Client: Any
InterceptionLibrary HookGlobal FunctionSocket LevelReal Network Server
CORS SupportManual/MockedManual/MockedN/A (Node)Real Browser Enforcement
HTTPSLogical MockLogical MockLogical MockReal TLS/SSL
Best ForUnit Testing AxiosUnit Testing FetchBackend/Node IntegrationE2E & Complex Integration

💡 The Big Picture

Choosing the right tool comes down to fidelity versus convenience.

axios-mock-adapter and fetch-mock are your go-to for fast, isolated unit tests. If you just need to verify that your component renders data correctly when an API call resolves, these are lightweight and easy to configure. Stick with them if your tests run entirely in a JS runtime and you don't care about network nuances.

nock is the power-user choice for Node.js developers. If you are testing a backend service or a Node script that talks to third-party APIs, nock ensures you are making the exact right calls with the right headers, regardless of whether you use Axios, Fetch, or raw HTTP.

mockttp is the heavy hitter for end-to-end (E2E) and integration testing. If your test runs in a real browser (via Cypress, Playwright, or Selenium) and you need to simulate CORS, SSL, or complex network conditions, mockttp is the only tool that provides a realistic enough environment to catch those edge cases. It trades a bit of setup complexity for unparalleled accuracy.

Final Thought: Don't over-engineer simple unit tests with a full mock server, but don't try to force a library-specific mock to solve complex network issues. Match the tool to the layer of the stack you are testing.

How to Choose: axios-mock-adapter vs fetch-mock vs mockttp vs nock

  • axios-mock-adapter:

    Choose axios-mock-adapter if your project relies exclusively on Axios for HTTP requests and you need a lightweight, easy-to-setup solution for unit tests. It is the best fit when you want to mock responses inline within your test files without configuring external servers or dealing with low-level network interception. Avoid this if you plan to migrate away from Axios soon, as the mocks are tightly coupled to the Axios instance.

  • fetch-mock:

    Select fetch-mock when your application uses the native fetch API or node-fetch and you require a pure JavaScript solution that works seamlessly in both browser and Node.js environments. It is ideal for teams wanting to avoid Axios-specific dependencies while maintaining simple, code-defined mock rules. However, be aware that it modifies the global fetch function, which can sometimes lead to side effects if not properly cleaned up between tests.

  • mockttp:

    Opt for mockttp when you need a realistic, end-to-end testing environment that simulates a real server, including support for CORS, HTTPS, and multiple concurrent clients. This is the superior choice for integration tests, cross-browser testing, or scenarios where your frontend runs in a real browser and needs to interact with a mock backend over the actual network stack. It is also the only viable option if you need to inspect or assert on raw HTTP traffic details beyond just the URL and body.

  • nock:

    Use nock if you are writing backend-heavy Node.js tests or need to intercept HTTP requests at the socket level regardless of the HTTP client library (Axios, Fetch, Request, etc.). It is perfect for verifying that your application makes the exact expected calls to external APIs with specific headers and payloads. Do not use nock for browser-based testing, as it relies on Node.js internal modules that are unavailable in browser environments.

README for axios-mock-adapter

axios-mock-adapter

Axios adapter that allows to easily mock requests

Installation

Using npm:

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

It's also available as a UMD build:

axios-mock-adapter works on Node as well as in a browser, it works with axios v0.17.0 and above.

Example

Mocking a GET request

const axios = require("axios");
const AxiosMockAdapter = require("axios-mock-adapter");

// This sets the mock adapter on the default instance
const mock = new AxiosMockAdapter(axios);

// Mock any GET request to /users
// arguments for reply are (status, data, headers)
mock.onGet("/users").reply(200, {
  users: [{ id: 1, name: "John Smith" }],
});

axios.get("/users").then(function (response) {
  console.log(response.data);
});

Mocking a GET request with specific parameters

const axios = require("axios");
const AxiosMockAdapter = require("axios-mock-adapter");

// This sets the mock adapter on the default instance
const mock = new AxiosMockAdapter(axios);

// Mock GET request to /users when param `searchText` is 'John'
// arguments for reply are (status, data, headers)
mock.onGet("/users", { params: { searchText: "John" } }).reply(200, {
  users: [{ id: 1, name: "John Smith" }],
});

axios
  .get("/users", { params: { searchText: "John" } })
  .then(function (response) {
    console.log(response.data);
  });

When using params, you must match all key/value pairs passed to that option.

To add a delay to responses, specify a delay amount (in milliseconds) when instantiating the adapter

// All requests using this instance will have a 2 seconds delay:
const mock = new AxiosMockAdapter(axiosInstance, { delayResponse: 2000 });

You can restore the original adapter (which will remove the mocking behavior)

mock.restore();

You can also reset the registered mock handlers with resetHandlers

mock.resetHandlers();

You can reset both registered mock handlers and history items with reset

mock.reset();

reset is different from restore in that restore removes the mocking from the axios instance completely, whereas reset only removes all mock handlers that were added with onGet, onPost, etc. but leaves the mocking in place.

Mock a low level network error

// Returns a failed promise with Error('Network Error');
mock.onGet("/users").networkError();

// networkErrorOnce can be used to mock a network error only once
mock.onGet("/users").networkErrorOnce();

Mock a network timeout

// Returns a failed promise with Error with code set to 'ECONNABORTED'
mock.onGet("/users").timeout();

// timeoutOnce can be used to mock a timeout only once
mock.onGet("/users").timeoutOnce();

Passing a function to reply

mock.onGet("/users").reply(function (config) {
  // `config` is the axios config and contains things like the url

  // return an array in the form of [status, data, headers]
  return [
    200,
    {
      users: [{ id: 1, name: "John Smith" }],
    },
  ];
});

Passing a function to reply that returns an axios request, essentially mocking a redirect

mock.onPost("/foo").reply(function (config) {
  return axios.get("/bar");
});

Using a regex

mock.onGet(/\/users\/\d+/).reply(function (config) {
  // the actual id can be grabbed from config.url

  return [200, {}];
});

Using variables in regex

const usersUri = "/users";
const url = new RegExp(`${usersUri}/*`);

mock.onGet(url).reply(200, users);

Specify no path to match by verb alone

// Reject all POST requests with HTTP 500
mock.onPost().reply(500);

Chaining is also supported

mock.onGet("/users").reply(200, users).onGet("/posts").reply(200, posts);

.replyOnce() can be used to let the mock only reply once

mock
  .onGet("/users")
  .replyOnce(200, users) // After the first request to /users, this handler is removed
  .onGet("/users")
  .replyOnce(500); // The second request to /users will have status code 500
// Any following request would return a 404 since there are
// no matching handlers left

Mocking any request to a given url

// mocks GET, POST, ... requests to /foo
mock.onAny("/foo").reply(200);

.onAny can be useful when you want to test for a specific order of requests

// Expected order of requests:
const responses = [
  ["GET", "/foo", 200, { foo: "bar" }],
  ["POST", "/bar", 200],
  ["PUT", "/baz", 200],
];

// Match ALL requests
mock.onAny().reply((config) => {
  const [method, url, ...response] = responses.shift();
  if (config.url === url && config.method.toUpperCase() === method)
    return response;
  // Unexpected request, error out
  return [500, {}];
});

Requests that do not map to a mock handler are rejected with a HTTP 404 response. Since handlers are matched in order, a final onAny() can be used to change the default behaviour

// Mock GET requests to /foo, reject all others with HTTP 500
mock.onGet("/foo").reply(200).onAny().reply(500);

Mocking a request with a specific request body/data

mock.onPut("/product", { id: 4, name: "foo" }).reply(204);

Using an asymmetric matcher, for example Jest matchers

mock
  .onPost(
    "/product",
    { id: 1 },
    {
      headers: expect.objectContaining({
        Authorization: expect.stringMatching(/^Basic /),
      })
    }
  )
  .reply(204);

Using a custom asymmetric matcher (any object that has a asymmetricMatch property)

mock
  .onPost("/product", {
    asymmetricMatch: function (actual) {
      return ["computer", "phone"].includes(actual["type"]);
    },
  })
  .reply(204);

.passThrough() forwards the matched request over network

// Mock POST requests to /api with HTTP 201, but forward
// GET requests to server
mock
  .onPost(/^\/api/)
  .reply(201)
  .onGet(/^\/api/)
  .passThrough();

Recall that the order of handlers is significant

// Mock specific requests, but let unmatched ones through
mock
  .onGet("/foo")
  .reply(200)
  .onPut("/bar", { xyz: "abc" })
  .reply(204)
  .onAny()
  .passThrough();

Note that passThrough requests are not subject to delaying by delayResponse.

If you set onNoMatch option to passthrough all requests would be forwarded over network by default

// Mock all requests to /foo with HTTP 200, but forward
// any others requests to server
const mock = new AxiosMockAdapter(axiosInstance, { onNoMatch: "passthrough" });

mock.onAny("/foo").reply(200);

Using onNoMatch option with throwException to throw an exception when a request is made without match any handler. It's helpful to debug your test mocks.

const mock = new AxiosMockAdapter(axiosInstance, { onNoMatch: "throwException" });

mock.onAny("/foo").reply(200);

axios.get("/unexistent-path");

// Exception message on console:
//
// Could not find mock for: 
// {
//   "method": "get",
//   "url": "http://localhost/unexistent-path"
// }

As of 1.7.0, reply function may return a Promise:

mock.onGet("/product").reply(function (config) {
  return new Promise(function (resolve, reject) {
    setTimeout(function () {
      if (Math.random() > 0.1) {
        resolve([200, { id: 4, name: "foo" }]);
      } else {
        // reject() reason will be passed as-is.
        // Use HTTP error status code to simulate server failure.
        resolve([500, { success: false }]);
      }
    }, 1000);
  });
});

Composing from multiple sources with Promises:

const normalAxios = axios.create();
const mockAxios = axios.create();
const mock = new AxiosMockAdapter(mockAxios);

mock
  .onGet("/orders")
  .reply(() =>
    Promise.all([
      normalAxios.get("/api/v1/orders").then((resp) => resp.data),
      normalAxios.get("/api/v2/orders").then((resp) => resp.data),
      { id: "-1", content: "extra row 1" },
      { id: "-2", content: "extra row 2" },
    ]).then((sources) => [
      200,
      sources.reduce((agg, source) => agg.concat(source)),
    ])
  );

History

The history property allows you to enumerate existing axios request objects. The property is an object of verb keys referencing arrays of request objects.

This is useful for testing.

describe("Feature", () => {
  it("requests an endpoint", (done) => {
    const mock = new AxiosMockAdapter(axios);
    mock.onPost("/endpoint").replyOnce(200);

    feature
      .request()
      .then(() => {
        expect(mock.history.post.length).toBe(1);
        expect(mock.history.post[0].data).toBe(JSON.stringify({ foo: "bar" }));
      })
      .then(done)
      .catch(done.fail);
  });
});

You can clear the history with resetHistory

mock.resetHistory();