msw vs nock vs faker vs axios-mock-adapter vs json-server vs miragejs
Mocking and Generating Data for Web Development
mswnockfakeraxios-mock-adapterjson-servermiragejsSimilar Packages:
Mocking and Generating Data for Web Development

Mocking and generating data libraries are essential tools in web development that help developers simulate API responses, create realistic test data, and improve the development workflow. These libraries are particularly useful for testing, prototyping, and building applications when the actual backend is not yet available or when you need to simulate specific scenarios. They can help ensure that your frontend code works correctly with various types of data and API responses, making your applications more robust and reliable. axios-mock-adapter is a library that allows you to mock Axios requests and responses, making it easy to test your code without relying on real APIs. faker is a popular library for generating fake data, such as names, addresses, and emails, which can be useful for testing and populating databases. json-server is a simple tool that creates a full REST API from a JSON file, allowing you to quickly set up a mock backend for your application. miragejs is a client-side mock server that intercepts network requests and serves predefined responses, making it ideal for testing and developing applications without a real backend. msw (Mock Service Worker) is a powerful library that uses service workers to intercept network requests and mock responses, providing a more realistic and flexible way to mock APIs. nock is a Node.js library for HTTP mocking and assertions, allowing you to intercept and mock HTTP requests in your tests, making it easier to test code that relies on external APIs.

Npm Package Weekly Downloads Trend
3 Years
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
msw7,215,89217,3234.79 MB614 days agoMIT
nock4,709,92313,046185 kB903 months agoMIT
faker2,033,430-10.1 MB--MIT
axios-mock-adapter1,783,5153,54467.9 kB92a year agoMIT
json-server343,87975,36234.4 kB721a year agoSEE LICENSE IN ./LICENSE
miragejs283,3405,5192.29 MB2122 years agoMIT
Feature Comparison: msw vs nock vs faker vs axios-mock-adapter vs json-server vs miragejs

Mocking HTTP Requests

  • msw:

    msw intercepts network requests at the service worker level and allows you to define mock responses for specific requests. It works with any HTTP client and provides a flexible API for mocking requests.

  • nock:

    nock intercepts HTTP requests in Node.js and allows you to specify how to respond to them. You can mock requests based on the URL, method, and request body, and you can also assert that specific requests were made.

  • faker:

    faker does not mock HTTP requests, but it can generate fake data that can be used in your requests, responses, or database seeding. It is a data generation library rather than a mocking tool.

  • axios-mock-adapter:

    axios-mock-adapter allows you to mock HTTP requests made with Axios by specifying the request URL, method, and response data. You can mock individual requests or set up global mocks that apply to all requests.

  • json-server:

    json-server creates a mock REST API that serves data from a JSON file. It automatically handles CRUD operations and can be configured to return specific data based on the request URL.

  • miragejs:

    miragejs intercepts HTTP requests made by your application and responds with predefined data. You can define routes, models, and serializers to control how requests are handled and what data is returned.

Data Generation

  • msw:

    msw does not generate data; it focuses on mocking requests and responses. You can use it with data generation libraries to create dynamic mock responses.

  • nock:

    nock does not generate data; it mocks HTTP requests and responses based on the specifications you provide. You can use it alongside data generation libraries to create realistic mock responses.

  • faker:

    faker excels at generating realistic fake data for a wide variety of use cases, including names, addresses, emails, and more. You can generate data on demand or create custom data generators.

  • axios-mock-adapter:

    axios-mock-adapter does not generate data; it simply mocks requests and responses. You can use it in conjunction with data generation libraries like faker to create realistic mock responses.

  • json-server:

    json-server serves data from a static JSON file, so the data must be provided in advance. You can combine it with faker or other data generation tools to create a JSON file with fake data.

  • miragejs:

    miragejs allows you to define models and relationships, which can be used to generate mock data dynamically. You can create custom data factories to generate data for your API responses.

Setup and Configuration

  • msw:

    msw requires setting up a service worker to intercept network requests. Once the service worker is registered, you can define your mock handlers in your application or test files.

  • nock:

    nock requires setup in your test files where you define the HTTP requests to mock. It is typically used in conjunction with testing frameworks like Mocha, Jest, or Jasmine.

  • faker:

    faker is easy to set up and use. You can import it and start generating fake data immediately. It requires no configuration, but you can customize the data generation process if needed.

  • axios-mock-adapter:

    axios-mock-adapter requires minimal setup and can be configured directly in your test files. You need to create an instance of the adapter and attach it to your Axios instance.

  • json-server:

    json-server requires a simple setup where you provide a JSON file and run a command to start the server. It can be configured using command-line options or a json-server configuration file.

  • miragejs:

    miragejs requires some initial setup to define your mock server, routes, and data models. It is typically integrated into your application during development and can be configured dynamically.

Integration with Testing Frameworks

  • msw:

    msw integrates well with testing frameworks like Jest, Cypress, and Testing Library. It allows you to mock API requests in your tests, making it easier to test components and functions that rely on external APIs.

  • nock:

    nock is designed for use in Node.js testing environments and integrates well with frameworks like Mocha, Jest, and Jasmine. It allows you to mock HTTP requests and assert that they were made as expected.

  • faker:

    faker can be used alongside any testing framework to generate fake data for tests. It is particularly useful for populating databases, creating test data, or simulating user input in your tests.

  • axios-mock-adapter:

    axios-mock-adapter integrates seamlessly with testing frameworks like Jest, Mocha, and Jasmine. You can use it to mock requests in your unit tests and assert that your code behaves correctly with the mocked responses.

  • json-server:

    json-server can be used in conjunction with testing frameworks to provide a mock API for integration tests. You can start the server before running your tests and stop it afterward.

  • miragejs:

    miragejs can be used with testing frameworks to mock API responses during tests. It is especially useful for testing components and applications that rely on network requests.

Ease of Use: Code Examples

  • msw:

    Mocking API Requests with msw

    import { setupWorker, rest } from 'msw';
    
    const worker = setupWorker(
      rest.get('/users', (req, res, ctx) => {
        return res(ctx.json([{ id: 1, name: 'John Doe' }]));
      })
    );
    
    // Start the service worker
    worker.start();
    
    // Now requests to /users will be mocked
    
  • nock:

    Mocking HTTP Requests with nock

    import nock from 'nock';
    import axios from 'axios';
    
    // Mock an HTTP request
    nock('https://api.example.com')
      .get('/users')
      .reply(200, [{ id: 1, name: 'John Doe' }]);
    
    // Make the request
    axios.get('https://api.example.com/users').then(response => {
      console.log(response.data); // [{ id: 1, name: 'John Doe' }]
    });
    
  • faker:

    Generating Fake Data with faker

    import { faker } from '@faker-js/faker';
    
    // Generate a random name
    const name = faker.name.findName();
    
    // Generate a random email
    const email = faker.internet.email();
    
    // Generate a random address
    const address = faker.address.streetAddress();
    
    console.log(`Name: ${name}`);
    console.log(`Email: ${email}`);
    console.log(`Address: ${address}`);
    
  • axios-mock-adapter:

    Mocking Axios Requests with axios-mock-adapter

    import axios from 'axios';
    import MockAdapter from 'axios-mock-adapter';
    
    const mock = new MockAdapter(axios);
    
    // Mock a GET request to /users
    mock.onGet('/users').reply(200, [{ id: 1, name: 'John Doe' }]);
    
    // Make the request
    axios.get('/users').then(response => {
      console.log(response.data); // [{ id: 1, name: 'John Doe' }]
    });
    
  • json-server:

    Creating a Mock API with json-server

    # Install json-server
    npm install -g json-server
    
    # Create a db.json file
    {
      "users": [
        { "id": 1, "name": "John Doe" }
      ]
    }
    
    # Start the json-server
    json-server --watch db.json
    
  • miragejs:

    Mocking API Requests with miragejs

    import { createServer } from 'miragejs';
    
    createServer({
      routes() {
        this.namespace = 'api';
    
        this.get('/users', () => {
          return [{ id: 1, name: 'John Doe' }];
        });
      },
    });
    
    // Now you can make requests to /api/users
    
How to Choose: msw vs nock vs faker vs axios-mock-adapter vs json-server vs miragejs
  • msw:

    Choose msw if you want to mock APIs at the network level using service workers. It provides a realistic mocking experience, supports both browser and Node.js environments, and is great for testing and development without changing your codebase significantly.

  • nock:

    Choose nock if you are writing tests for Node.js applications and need to mock HTTP requests and responses. It is particularly useful for testing code that interacts with external APIs, as it allows you to assert that specific requests are made.

  • faker:

    Choose faker if you need to generate large amounts of realistic-looking fake data for testing, seeding databases, or populating forms. It offers a wide range of data generators and is highly customizable.

  • axios-mock-adapter:

    Choose axios-mock-adapter if you are using Axios for making HTTP requests and need a simple way to mock specific requests and responses in your tests. It integrates seamlessly with Axios and allows for fine-grained control over mocking behavior.

  • json-server:

    Choose json-server if you need a quick and easy way to create a RESTful API for prototyping, testing, or developing front-end applications. It requires minimal setup and can serve data from a static JSON file.

  • miragejs:

    Choose miragejs if you want to create a fully customizable mock server that can handle complex routing, data relationships, and dynamic responses. It is particularly useful for developing applications with rich interactions and requires more control over the mocked API.

README for msw

The Mock Service Worker logo

Mock Service Worker

Industry standard API mocking for JavaScript.

Join our 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 of the library, but there's no better place to start with Mock Service Worker than its official documentation.

Examples

Courses

We've partnered with Egghead to bring you quality paid materials to learn the best practices of API mocking on the web. Please give them a shot! The royalties earned from them help sustain the project's development. Thank you.

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 or bloated configurations.

Usage example

// 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 mocking 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 request handlers execute 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

Here's an example of using Mock Service Worker while developing your Express server:

import express from 'express'
import { http, HttpResponse } from 'msw'
import { setupServer } from 'msw/node'

const app = express()
const server = setupServer()

app.get(
  '/checkout/session',
  server.boundary((req, res) => {
    // Describe the network for this Express route.
    server.use(
      http.get(
        'https://api.stripe.com/v1/checkout/sessions/:id',
        ({ params }) => {
          return HttpResponse.json({
            id: params.id,
            mode: 'payment',
            status: 'open',
          })
        },
      ),
    )

    // Continue with processing the checkout session.
    handleSession(req, res)
  }),
)

This example showcases server.boundary() to scope request interception to a particular closure, which is extremely handy!

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, Netflix, and countless others. Despite that, it remains a hobby project maintained in a 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)