Which is Better HTTP Request Mocking Libraries?
msw vs nock vs axios-mock-adapter vs fetch-mock
1 Year
mswnockaxios-mock-adapterfetch-mockSimilar Packages:
What's HTTP Request Mocking Libraries?

HTTP request mocking libraries are essential tools in web development that allow developers to simulate API responses for testing purposes. They enable developers to create controlled environments where they can test their applications without relying on actual backend services. This is particularly useful for unit testing, integration testing, and end-to-end testing, as it helps in isolating the frontend from backend dependencies and ensures that tests can be run consistently and reliably. Each library offers unique features and methodologies for mocking HTTP requests, catering to different testing needs and preferences.

NPM Package Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
msw3,526,03815,7424.07 MB6613 days agoMIT
nock3,079,90012,701187 kB72a month agoMIT
axios-mock-adapter1,477,1013,45069.9 kB852 months agoMIT
fetch-mock811,6631,256398 kB108 days agoMIT
Feature Comparison: msw vs nock vs axios-mock-adapter vs fetch-mock

Integration

  • msw: MSW operates at the network level, intercepting requests made by the Fetch API or XMLHttpRequest. This allows for a more realistic simulation of API interactions, making it suitable for both unit and integration tests. It can also be integrated with popular testing libraries like Jest and Testing Library.
  • nock: Nock is specifically designed for Node.js applications and provides a powerful way to mock HTTP requests. It allows you to define expected requests and their responses, making it ideal for testing server-side code and APIs without making actual network calls.
  • axios-mock-adapter: Axios-mock-adapter is designed to work specifically with Axios, making it easy to mock requests made through Axios instances. This tight integration allows you to set up mocks directly on your Axios instance, providing a straightforward approach for testing components that depend on Axios for data fetching.
  • fetch-mock: Fetch-mock is built to work with the Fetch API, allowing you to mock fetch requests easily. It provides a flexible API for defining responses and can be used in various testing frameworks, making it versatile for different testing setups.

Flexibility

  • msw: MSW's flexibility lies in its ability to mock any type of network request, including REST and GraphQL. You can define handlers for various endpoints and response scenarios, making it easy to simulate complex API interactions and error handling.
  • nock: Nock allows for extensive customization of request matching and response behavior. You can match requests based on URL, HTTP method, headers, and even request body, providing a high level of control over your mocked interactions.
  • axios-mock-adapter: Axios-mock-adapter offers a flexible way to define request matching and response behaviors. You can easily configure it to return different responses based on request parameters, headers, and more, allowing for comprehensive testing scenarios.
  • fetch-mock: Fetch-mock provides a highly flexible API for mocking responses. You can define responses based on URL patterns, request methods, and even request bodies, giving you fine-grained control over how your mocks behave during tests.

Testing Environment

  • msw: MSW is ideal for integration testing as it intercepts actual network requests, providing a realistic testing environment. It allows you to test how your application interacts with APIs in a way that closely resembles production behavior, making it great for end-to-end testing.
  • nock: Nock is best suited for testing server-side applications in Node.js. It allows you to simulate HTTP requests and responses, making it easy to test how your server handles various API interactions without relying on external services.
  • axios-mock-adapter: Axios-mock-adapter is primarily used in unit tests where you want to isolate components that rely on Axios for data fetching. It allows you to simulate various API responses without making actual network calls, ensuring your tests run quickly and reliably.
  • fetch-mock: Fetch-mock is suitable for both unit and integration tests. It allows you to mock fetch requests in a controlled manner, making it easy to simulate different scenarios and test how your application handles various API responses.

Ease of Use

  • msw: MSW has a slightly steeper learning curve due to its network-level interception capabilities, but it offers comprehensive documentation and examples, making it easier to adopt for those familiar with modern testing practices.
  • nock: Nock is easy to use for Node.js developers, with a clear API for defining request expectations and responses. However, it may require more setup compared to client-side libraries, as it is focused on server-side testing.
  • axios-mock-adapter: Axios-mock-adapter is straightforward to set up and use, especially for developers already familiar with Axios. Its API is intuitive, allowing for quick configuration of mocks and easy integration into existing test suites.
  • fetch-mock: Fetch-mock is user-friendly and provides a simple API for defining mocks. Its flexibility and ease of use make it a popular choice for developers looking to mock fetch requests without much overhead.

Community and Support

  • msw: MSW has gained significant traction in the developer community due to its innovative approach to mocking. It is well-documented and has a supportive community, making it a great choice for modern applications.
  • nock: Nock has a strong presence in the Node.js community and is widely used for testing HTTP requests. It has good documentation and community support, making it a reliable choice for server-side testing.
  • axios-mock-adapter: Axios-mock-adapter has a solid community and is widely used among developers who utilize Axios. It benefits from the popularity of Axios, ensuring good support and regular updates.
  • fetch-mock: Fetch-mock has a growing community and is actively maintained. Its popularity among developers using the Fetch API ensures that you can find resources and support easily.
How to Choose: msw vs nock vs axios-mock-adapter vs fetch-mock
  • msw: Opt for MSW (Mock Service Worker) if you want to mock both REST and GraphQL APIs at the network level. MSW intercepts actual network requests in the browser or Node.js, providing a more realistic testing environment. It is particularly useful for integration tests and can be used in both frontend and backend applications.
  • nock: Choose nock if you are working in a Node.js environment and need to mock HTTP requests for testing server-side code. Nock allows you to intercept and modify HTTP requests, making it ideal for testing APIs and services without making actual network calls.
  • axios-mock-adapter: Choose axios-mock-adapter if you are already using Axios for making HTTP requests in your application. It seamlessly integrates with Axios and allows for easy mocking of requests and responses, making it ideal for unit testing components that rely on Axios.
  • fetch-mock: Select fetch-mock if your application uses the Fetch API for making HTTP requests. It provides a simple and flexible API for mocking fetch calls, allowing you to simulate various response scenarios and control the behavior of your fetch requests during testing.
README for msw

MSW 2.0 is finally here! 🎉 Read the Release notes and please follow the Migration guidelines to upgrade. If you're having any questions while upgrading, please reach out in our Discord server.

We've also recorded the most comprehensive introduction to MSW ever. Learn how to mock APIs like a pro in our official video course:

Mock REST and GraphQL APIs with Mock Service Worker

Mock Service Worker logo

Mock Service Worker

Mock Service Worker (MSW) is a seamless REST/GraphQL API mocking library for browser and Node.js.

Package version Downloads per month Discord server



Features

  • Seamless. A dedicated layer of requests interception at your disposal. Keep your application's code and tests unaware of whether something is mocked or not.
  • Deviation-free. Request the same production resources and test the actual behavior of your app. Augment an existing API, or design it as you go when there is none.
  • Familiar & Powerful. Use Express-like routing syntax to intercept requests. Use parameters, wildcards, and regular expressions to match requests, and respond with necessary status codes, headers, cookies, delays, or completely custom resolvers.

"I found MSW and was thrilled that not only could I still see the mocked responses in my DevTools, but that the mocks didn't have to be written in a Service Worker and could instead live alongside the rest of my app. This made it silly easy to adopt. The fact that I can use it for testing as well makes MSW a huge productivity booster."

Kent C. Dodds

Documentation

This README will give you a brief overview on the library but there's no better place to start with Mock Service Worker than its official documentation.

Examples

Browser

How does it work?

In-browser usage is what sets Mock Service Worker apart from other tools. Utilizing the Service Worker API, which can intercept requests for the purpose of caching, Mock Service Worker responds to intercepted requests with your mock definition on the network level. This way your application knows nothing about the mocking.

Take a look at this quick presentation on how Mock Service Worker functions in a browser:

What is Mock Service Worker?

How is it different?

  • This library intercepts requests on the network level, which means after they have been performed and "left" your application. As a result, the entirety of your code runs, giving you more confidence when mocking;
  • Imagine your application as a box. Every API mocking library out there opens your box and removes the part that does the request, placing a blackbox in its stead. Mock Service Worker leaves your box intact, 1-1 as it is in production. Instead, MSW lives in a separate box next to yours;
  • No more stubbing of fetch, axios, react-query, you-name-it;
  • You can reuse the same mock definition for the unit, integration, and E2E testing. Did we mention local development and debugging? Yep. All running against the same network description without the need for adapters of bloated configurations.

Usage example

// src/mocks.js
// 1. Import the library.
import { http, HttpResponse } from 'msw'
import { setupWorker } from 'msw/browser'

// 2. Describe network behavior with request handlers.
const worker = setupWorker(
  http.get('https://github.com/octocat', ({ request, params, cookies }) => {
    return HttpResponse.json(
      {
        message: 'Mocked response',
      },
      {
        status: 202,
        statusText: 'Mocked status',
      },
    )
  }),
)

// 3. Start request interception by starting the Service Worker.
await worker.start()

Performing a GET https://github.com/octocat request in your application will result into a mocked response that you can inspect in your browser's "Network" tab:

Chrome DevTools Network screenshot with the request mocked

Tip: Did you know that although Service Worker runs in a separate thread, your mock definition executes entirely on the client? This way you can use the same languages, like TypeScript, third-party libraries, and internal logic to create the mocks you need.

Node.js

How does it work?

There's no such thing as Service Workers in Node.js. Instead, MSW implements a low-level interception algorithm that can utilize the very same request handlers you have for the browser. This blends the boundary between environments, allowing you to focus on your network behaviors.

How is it different?

  • Does not stub fetch, axios, etc. As a result, your tests know nothing about mocking;
  • You can reuse the same request handlers for local development and debugging, as well as for testing. Truly a single source of truth for your network behavior across all environments and all tools.

Usage example

Take a look at the example of an integration test in Vitest that uses React Testing Library and Mock Service Worker:

// test/Dashboard.test.js

import React from 'react'
import { http, HttpResponse } from 'msw'
import { setupServer } from 'msw/node'
import { render, screen, waitFor } from '@testing-library/react'
import Dashboard from '../src/components/Dashboard'

const server = setupServer(
  // Describe network behavior with request handlers.
  // Tip: move the handlers into their own module and
  // import it across your browser and Node.js setups!
  http.get('/posts', ({ request, params, cookies }) => {
    return HttpResponse.json([
      {
        id: 'f8dd058f-9006-4174-8d49-e3086bc39c21',
        title: `Avoid Nesting When You're Testing`,
      },
      {
        id: '8ac96078-6434-4959-80ed-cc834e7fef61',
        title: `How I Built A Modern Website In 2021`,
      },
    ])
  }),
)

// Enable request interception.
beforeAll(() => server.listen())

// Reset handlers so that each test could alter them
// without affecting other, unrelated tests.
afterEach(() => server.resetHandlers())

// Don't forget to clean up afterwards.
afterAll(() => server.close())

it('displays the list of recent posts', async () => {
  render(<Dashboard />)

  // 🕗 Wait for the posts request to be finished.
  await waitFor(() => {
    expect(
      screen.getByLabelText('Fetching latest posts...'),
    ).not.toBeInTheDocument()
  })

  // ✅ Assert that the correct posts have loaded.
  expect(
    screen.getByRole('link', { name: /Avoid Nesting When You're Testing/ }),
  ).toBeVisible()

  expect(
    screen.getByRole('link', { name: /How I Built A Modern Website In 2021/ }),
  ).toBeVisible()
})

Don't get overwhelmed! We've prepared a step-by-step Getting started tutorial that you can follow to learn how to integrate Mock Service Worker into your project.

Despite the API being called setupServer, there are no actual servers involved! The name was chosen for familiarity, and the API was designed to resemble operating with an actual server.

Sponsors

Mock Service Worker is trusted by hundreds of thousands of engineers around the globe. It's used by companies like Google, Microsoft, Spotify, Amazon, and countless others. Despite that, this library remains a hobby project maintained in spare time and has no opportunity to financially support even a single full-time contributor.

You can change that! Consider sponsoring the effort behind one of the most innovative approaches around API mocking. Raise a topic of open source sponsorships with your boss and colleagues. Let's build sustainable open source together!

Golden Sponsors

Become our golden sponsor and get featured right here, enjoying other perks like issue prioritization and a personal consulting session with us.

Learn more on our GitHub Sponsors profile.


GitHub Codacy Workleap Chromatic

Silver Sponsors

Become our silver sponsor and get your profile image and link featured right here.

Learn more on our GitHub Sponsors profile.


Replay Codemod

Bronze Sponsors

Become our bronze sponsor and get your profile image and link featured in this section.

Learn more on our GitHub Sponsors profile.


Materialize Trigger.dev Vital

Awards & Mentions

We've been extremely humbled to receive awards and mentions from the community for all the innovation and reach Mock Service Worker brings to the JavaScript ecosystem.

Technology Radar

Solution Worth Pursuing

Technology Radar (2020–2021)

Open Source Awards 2020

The Most Exciting Use of Technology

Open Source Awards (2020)