axios-mock-adapter vs fetch-mock vs mockttp vs nock
HTTP Mocking Libraries
axios-mock-adapterfetch-mockmockttpnockSimilar Packages:

HTTP Mocking Libraries

HTTP mocking libraries are essential tools in web development that allow developers to simulate HTTP requests and responses for testing purposes. They enable developers to create controlled environments for testing API interactions without relying on actual network calls. This is particularly useful for unit testing, integration testing, and ensuring that applications behave as expected under various scenarios. By using these libraries, developers can isolate their tests from external factors, leading to more reliable and faster test execution. Each library has its unique features and use cases, making it important to choose the right one based on project requirements.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
axios-mock-adapter03,55167.9 kB96a year agoMIT
fetch-mock01,309157 kB64 months agoMIT
mockttp08501.84 MB404 months agoApache-2.0
nock013,081185 kB8317 days agoMIT

Feature Comparison: axios-mock-adapter vs fetch-mock vs mockttp vs nock

Integration

  • axios-mock-adapter:

    axios-mock-adapter is specifically designed to work with Axios, making it easy to mock Axios requests without additional configuration. It allows you to intercept requests and provide custom responses, ensuring that your tests are closely aligned with your actual application logic.

  • fetch-mock:

    fetch-mock integrates directly with the Fetch API, allowing you to mock fetch calls seamlessly. Its API is straightforward, making it easy to set up mocks for various scenarios, including error handling and different response types.

  • mockttp:

    mockttp is designed to be agnostic of the HTTP client, meaning it can be used with any library that makes HTTP requests. This flexibility allows you to mock requests in a variety of testing environments, making it suitable for diverse projects.

  • nock:

    nock is built for Node.js and integrates well with HTTP requests made using the native http and https modules. It allows you to create mocks that can simulate a wide range of HTTP interactions, making it a powerful tool for backend testing.

Features

  • axios-mock-adapter:

    axios-mock-adapter provides features like request matching, response delays, and the ability to simulate network errors. It allows for precise control over how requests are handled, making it easy to test various scenarios without hitting the actual API.

  • fetch-mock:

    fetch-mock includes features such as response matching based on URL patterns, support for promises, and the ability to simulate different response statuses. It also allows for fine-grained control over how requests are intercepted and responded to, enhancing testing capabilities.

  • mockttp:

    mockttp offers advanced features like request interception, response manipulation, and the ability to record and replay HTTP interactions. It supports both HTTP and HTTPS, allowing for comprehensive testing of secure connections, making it suitable for complex applications.

  • nock:

    nock allows you to define HTTP request expectations and provides a simple API for setting up mocks. It supports features like automatic response serialization and the ability to simulate delays, making it effective for testing asynchronous operations.

Ease of Use

  • axios-mock-adapter:

    axios-mock-adapter is easy to set up, especially for developers already familiar with Axios. Its API is intuitive, allowing for quick implementation of mocks with minimal boilerplate code, making it beginner-friendly.

  • fetch-mock:

    fetch-mock is straightforward to use and provides a clear API for mocking fetch requests. Its simplicity makes it accessible for developers who are new to testing or mocking, allowing for rapid test development.

  • mockttp:

    mockttp has a slightly steeper learning curve due to its advanced features, but it offers comprehensive documentation that helps users get up to speed quickly. Its flexibility can be a significant advantage for more complex testing scenarios.

  • nock:

    nock is well-documented and easy to use for Node.js developers. Its API is designed to be straightforward, allowing developers to quickly set up mocks and focus on writing tests rather than configuration.

Community and Support

  • axios-mock-adapter:

    axios-mock-adapter benefits from the large Axios community, which means there are plenty of resources, tutorials, and examples available to help developers. This community support can be invaluable for troubleshooting and learning best practices.

  • fetch-mock:

    fetch-mock has a growing community and is well-supported with documentation and examples. While it may not be as large as Axios, it still provides sufficient resources for developers to find help and guidance.

  • mockttp:

    mockttp is gaining popularity and has a supportive community, with active development and updates. Its documentation is thorough, providing users with the information they need to utilize its advanced features effectively.

  • nock:

    nock has a robust community and is widely used in the Node.js ecosystem. It is well-documented and frequently updated, ensuring that developers have access to the latest features and best practices.

Performance

  • axios-mock-adapter:

    axios-mock-adapter is lightweight and optimized for performance, ensuring that tests run quickly without significant overhead. Its integration with Axios means that it can leverage Axios's performance optimizations as well.

  • fetch-mock:

    fetch-mock is designed to be efficient and minimizes performance overhead during tests. It allows for quick setup and teardown of mocks, ensuring that tests remain fast and responsive.

  • mockttp:

    mockttp is built for performance, allowing for high-speed mocking of HTTP requests. Its ability to handle complex scenarios without significant slowdowns makes it suitable for large applications with extensive testing needs.

  • nock:

    nock is efficient in mocking HTTP requests and is designed to minimize performance impacts during testing. It allows for quick responses and can handle a large number of requests without degrading test performance.

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

  • axios-mock-adapter:

    Choose axios-mock-adapter if you are already using Axios for making HTTP requests in your application. It integrates seamlessly with Axios and allows you to mock requests and responses easily, making it ideal for projects that already utilize Axios.

  • fetch-mock:

    Select fetch-mock if your application uses the Fetch API for making HTTP requests. It provides a simple and flexible way to mock fetch calls, making it suitable for testing applications that rely on the Fetch API.

  • mockttp:

    Opt for mockttp if you need a powerful and flexible mocking library that can work with any HTTP client. It supports both HTTP and HTTPS and allows for advanced features like request interception and response manipulation, making it great for complex testing scenarios.

  • nock:

    Use nock if you want to mock HTTP requests in Node.js applications. It is specifically designed for Node.js and allows you to intercept and respond to HTTP requests, making it a solid choice for backend testing.

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();