msw vs nock vs faker vs axios-mock-adapter vs miragejs vs json-server
Mocking and Testing Libraries for Web Development Comparison
1 Year
mswnockfakeraxios-mock-adaptermiragejsjson-serverSimilar Packages:
What's Mocking and Testing Libraries for Web Development?

These libraries are designed to facilitate testing and development in web applications by providing tools to simulate server responses, generate fake data, and intercept HTTP requests. They help developers create robust applications by allowing them to test various scenarios without relying on a live backend. This is particularly useful for frontend development, where backend services may not be available or fully implemented.

Package Weekly Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
msw4,289,02116,3984.47 MB602 days agoMIT
nock3,987,63912,853183 kB8616 days agoMIT
faker2,132,009-10.1 MB--MIT
axios-mock-adapter1,572,9963,48867.9 kB864 months agoMIT
miragejs343,4305,4452.29 MB201a year agoMIT
json-server284,75173,68034.4 kB7095 months agoSEE LICENSE IN ./LICENSE
Feature Comparison: msw vs nock vs faker vs axios-mock-adapter vs miragejs vs json-server

Integration

  • msw:

    Works with any JavaScript application, including React, Vue, and Angular, by intercepting network requests at the service worker level, providing a flexible integration method.

  • nock:

    Integrates well with Node.js testing frameworks like Mocha and Jest, allowing for easy mocking of HTTP requests in server-side applications.

  • faker:

    Standalone library that can be integrated into any testing framework or environment. It does not depend on any specific HTTP client or library, making it versatile for various use cases.

  • axios-mock-adapter:

    Integrates directly with Axios, allowing you to mock requests made with Axios easily. This makes it a natural choice for projects already using Axios for HTTP requests.

  • miragejs:

    Designed to work seamlessly with frontend frameworks like React, Vue, and Angular, allowing for easy integration into modern web applications.

  • json-server:

    Provides a simple setup to create a REST API from a JSON file, allowing for quick integration into frontend applications without additional configuration.

Complexity

  • msw:

    Moderate complexity due to its service worker setup, but offers powerful capabilities for intercepting requests and simulating real-world scenarios.

  • nock:

    Requires some understanding of HTTP requests and responses, but provides extensive capabilities for mocking and testing server interactions.

  • faker:

    Easy to use with a simple API for generating various types of fake data. It requires minimal setup and can be used immediately.

  • axios-mock-adapter:

    Simple to use with a straightforward API, making it easy for developers to mock requests without a steep learning curve.

  • miragejs:

    More complex than json-server, as it allows for detailed route definitions and response handling, but provides greater flexibility and realism in API simulation.

  • json-server:

    Very easy to set up and use, requiring only a JSON file to create a fully functional REST API. Ideal for rapid prototyping.

Use Cases

  • msw:

    Great for both unit and integration testing, as it allows you to simulate real-world network conditions and responses, making tests more reliable.

  • nock:

    Best for testing Node.js applications that rely on external APIs, allowing you to simulate and control API responses during tests.

  • faker:

    Ideal for populating databases or generating test data for applications, especially in scenarios where realistic data is needed for testing.

  • axios-mock-adapter:

    Best suited for unit testing components that rely on Axios for data fetching, allowing you to simulate various API responses easily.

  • miragejs:

    Excellent for frontend applications that require a realistic API simulation, allowing for complex interactions and state management during development.

  • json-server:

    Perfect for frontend developers who need a quick mock backend to test their applications without a real server.

Realism

  • msw:

    Simulates real network requests and responses, providing a high level of realism in testing scenarios, making it suitable for both unit and integration tests.

  • nock:

    Allows for detailed control over HTTP interactions, providing a realistic testing environment for server-side applications.

  • faker:

    Generates realistic data but does not simulate API interactions; primarily focused on data generation.

  • axios-mock-adapter:

    Provides a simple way to mock responses, but may not fully simulate the complexities of real-world API interactions.

  • miragejs:

    Offers a high level of realism by allowing you to define complex routes and responses, simulating a real backend service effectively.

  • json-server:

    Creates a REST API that behaves like a real server, providing a realistic testing environment for frontend applications.

Community and Support

  • msw:

    Rapidly gaining popularity with a strong community and excellent documentation, making it easy to get started and find support.

  • nock:

    Well-established in the Node.js community with extensive documentation and examples, making it a reliable choice for mocking HTTP requests.

  • faker:

    Widely used with extensive documentation and community support, making it easy to find help and examples.

  • axios-mock-adapter:

    Has a supportive community due to its integration with Axios, making it easy to find resources and examples.

  • miragejs:

    Growing community with good documentation, providing support for developers looking to implement realistic API simulations.

  • json-server:

    Popular among frontend developers, with a strong community and plenty of resources available for setup and usage.

How to Choose: msw vs nock vs faker vs axios-mock-adapter vs miragejs vs json-server
  • msw:

    Choose msw (Mock Service Worker) if you want to intercept network requests at the service worker level. This approach allows you to mock API responses in a way that closely resembles real-world scenarios, making it suitable for both unit and integration testing.

  • nock:

    Select nock if you need to intercept and mock HTTP requests in Node.js applications. It is particularly useful for testing server-side code, allowing you to simulate responses from external APIs without making actual network calls.

  • faker:

    Select faker if you need to generate large amounts of fake data for testing purposes. It provides a wide range of data types and formats, making it ideal for populating databases or creating realistic test scenarios without manual data entry.

  • axios-mock-adapter:

    Choose axios-mock-adapter if you are already using Axios for making HTTP requests and want a simple way to mock those requests in your tests. It integrates seamlessly with Axios and allows you to define responses for specific requests easily.

  • miragejs:

    Use miragejs if you need a more sophisticated solution for mocking APIs in a frontend application. It allows you to define routes, models, and responses, providing a more realistic simulation of a backend service and enabling complex interactions.

  • json-server:

    Opt for json-server if you want a quick and easy way to set up a REST API for testing. It allows you to create a full fake REST API with minimal configuration, making it perfect for prototyping and frontend development.

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

Industry standard API mocking for JavaScript.

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
StackBlitz

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 Ryan Magoon

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)