Convert Figma logo to code with AI

mswjs logomsw

Seamless REST/GraphQL API mocking library for browser and Node.js.

15,604
498
15,604
66

Top Related Projects

The all-batteries-included GitHub SDK for Browsers, Node.js, and Deno.

Get a full fake REST API with zero coding in less than 30 seconds (seriously)

12,673

HTTP server mocking and expectations library for Node.js

46,661

Fast, easy and reliable testing for anything that runs in a browser.

1,606

JS version of Pact. Pact is a contract testing framework for HTTP APIs and non-HTTP asynchronous messaging systems.

Quick Overview

MSW (Mock Service Worker) is a powerful API mocking library for browser and Node.js. It intercepts requests on the network level, allowing developers to mock API responses without modifying their application code. This makes it ideal for testing, development, and debugging scenarios.

Pros

  • Seamless integration with existing projects, requiring minimal setup
  • Works in both browser and Node.js environments
  • Supports REST and GraphQL APIs
  • Enables realistic testing scenarios by simulating network conditions

Cons

  • Learning curve for complex mocking scenarios
  • May introduce overhead in large-scale applications
  • Potential for conflicts with other network intercepting tools
  • Limited support for some less common API protocols

Code Examples

  1. Mocking a REST API response:
import { rest, setupWorker } from 'msw'

const handlers = [
  rest.get('/api/users', (req, res, ctx) => {
    return res(
      ctx.status(200),
      ctx.json([
        { id: 1, name: 'John Doe' },
        { id: 2, name: 'Jane Smith' },
      ])
    )
  }),
]

const worker = setupWorker(...handlers)
worker.start()
  1. Mocking a GraphQL API response:
import { graphql, setupWorker } from 'msw'

const handlers = [
  graphql.query('GetUser', (req, res, ctx) => {
    return res(
      ctx.data({
        user: {
          id: '1',
          name: 'John Doe',
          email: 'john@example.com',
        },
      })
    )
  }),
]

const worker = setupWorker(...handlers)
worker.start()
  1. Simulating network error:
import { rest, setupWorker } from 'msw'

const handlers = [
  rest.get('/api/data', (req, res, ctx) => {
    return res(
      ctx.status(500),
      ctx.json({ message: 'Internal Server Error' })
    )
  }),
]

const worker = setupWorker(...handlers)
worker.start()

Getting Started

  1. Install MSW:

    npm install msw --save-dev
    
  2. Create a mocks directory in your project root and add a handlers.js file:

    import { rest } from 'msw'
    
    export const handlers = [
      rest.get('/api/users', (req, res, ctx) => {
        return res(ctx.json([{ id: 1, name: 'John Doe' }]))
      }),
    ]
    
  3. Create a browser.js file in the mocks directory:

    import { setupWorker } from 'msw'
    import { handlers } from './handlers'
    
    export const worker = setupWorker(...handlers)
    
  4. Initialize MSW in your application entry point:

    import { worker } from './mocks/browser'
    
    if (process.env.NODE_ENV === 'development') {
      worker.start()
    }
    

Now you're ready to use MSW for mocking API responses in your application!

Competitor Comparisons

The all-batteries-included GitHub SDK for Browsers, Node.js, and Deno.

Pros of Octokit.js

  • Specifically designed for GitHub API interactions, offering comprehensive coverage of GitHub features
  • Provides type definitions for TypeScript users, enhancing developer experience
  • Offers modular architecture, allowing users to import only needed components

Cons of Octokit.js

  • Limited to GitHub API, not suitable for mocking other APIs or services
  • Requires more setup and configuration for testing scenarios compared to MSW
  • May have a steeper learning curve for developers unfamiliar with GitHub's API structure

Code Comparison

MSW (Mock Service Worker):

import { rest } from 'msw'
import { setupServer } from 'msw/node'

const server = setupServer(
  rest.get('/api/user', (req, res, ctx) => {
    return res(ctx.json({ name: 'John Doe' }))
  })
)

Octokit.js:

import { Octokit } from '@octokit/rest'

const octokit = new Octokit({ auth: 'YOUR-TOKEN' })

const { data } = await octokit.rest.users.getAuthenticated()
console.log(data.login)

While MSW focuses on mocking HTTP requests for testing and development, Octokit.js is tailored for interacting with GitHub's API. MSW offers more flexibility for general API mocking, whereas Octokit.js provides a more specialized and feature-rich experience for GitHub-specific tasks.

Get a full fake REST API with zero coding in less than 30 seconds (seriously)

Pros of json-server

  • Provides a full REST API with zero coding
  • Supports custom routes and middlewares
  • Can be used as a Node.js module or command-line tool

Cons of json-server

  • Limited to REST API simulation only
  • Doesn't support GraphQL or WebSocket mocking
  • Less flexibility for complex request interception scenarios

Code Comparison

json-server:

const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
server.use(router)
server.listen(3000)

msw:

import { setupServer } from 'msw/node'
import { rest } from 'msw'

const server = setupServer(
  rest.get('/api/users', (req, res, ctx) => {
    return res(ctx.json([{ id: 1, name: 'John' }]))
  })
)
server.listen()

Key Differences

  • json-server focuses on creating a mock REST API from a JSON file, while msw provides a more flexible approach to mocking various types of network requests.
  • msw integrates seamlessly with both browser and Node.js environments, offering a unified API mocking solution for frontend and backend testing.
  • json-server is easier to set up for simple REST API mocking scenarios, while msw offers more advanced features for complex request interception and response manipulation.
  • msw supports mocking GraphQL and WebSocket requests, which json-server does not provide.

Both tools have their strengths and are suitable for different use cases, with json-server excelling in quick REST API prototyping and msw offering more comprehensive request mocking capabilities.

12,673

HTTP server mocking and expectations library for Node.js

Pros of Nock

  • Simpler setup and usage for Node.js environments
  • Extensive matching options for intercepting HTTP requests
  • Lightweight and focused solely on HTTP mocking

Cons of Nock

  • Limited to Node.js environments, not suitable for browser testing
  • Requires more manual setup for complex scenarios
  • Less intuitive for developers used to working with service workers

Code Comparison

Nock:

const nock = require('nock');

nock('https://api.example.com')
  .get('/users')
  .reply(200, { users: ['Alice', 'Bob'] });

MSW:

import { rest, setupWorker } from 'msw';

const worker = setupWorker(
  rest.get('https://api.example.com/users', (req, res, ctx) => {
    return res(ctx.json({ users: ['Alice', 'Bob'] }));
  })
);

Both MSW and Nock are popular libraries for mocking HTTP requests in JavaScript applications. MSW offers a more versatile solution that works in both Node.js and browser environments, using service workers to intercept requests. It provides a more realistic testing experience and can be used for both development and testing purposes.

Nock, on the other hand, is specifically designed for Node.js and offers a straightforward approach to HTTP mocking. It's particularly useful for unit testing and scenarios where browser compatibility is not required. The choice between the two depends on the specific needs of your project, such as the target environment and the complexity of your mocking requirements.

46,661

Fast, easy and reliable testing for anything that runs in a browser.

Pros of Cypress

  • End-to-end testing framework with a rich set of built-in commands and assertions
  • Real-time browser testing with automatic waiting and retry mechanisms
  • Extensive documentation and active community support

Cons of Cypress

  • Limited to testing web applications within a browser environment
  • Can be slower for large test suites compared to unit testing frameworks
  • Requires more setup and configuration for complex scenarios

Code Comparison

MSW (Mock Service Worker):

import { rest } from 'msw'
import { setupServer } from 'msw/node'

const server = setupServer(
  rest.get('/api/user', (req, res, ctx) => {
    return res(ctx.json({ name: 'John Doe' }))
  })
)

Cypress:

describe('User API', () => {
  it('fetches user data', () => {
    cy.intercept('GET', '/api/user', { fixture: 'user.json' })
    cy.visit('/user-profile')
    cy.get('.user-name').should('contain', 'John Doe')
  })
})

Key Differences

  • MSW focuses on mocking API requests at the network level, while Cypress provides a complete end-to-end testing solution
  • MSW can be used in both browser and Node.js environments, whereas Cypress is primarily for browser-based testing
  • Cypress offers a more comprehensive set of commands for interacting with web elements and asserting UI behavior
1,606

JS version of Pact. Pact is a contract testing framework for HTTP APIs and non-HTTP asynchronous messaging systems.

Pros of Pact

  • Supports contract testing between multiple services
  • Generates contract files that can be shared between consumer and provider
  • Integrates well with CI/CD pipelines for automated contract verification

Cons of Pact

  • Steeper learning curve due to its specific contract testing concepts
  • Requires more setup and configuration compared to MSW
  • Limited support for mocking GraphQL APIs

Code Comparison

MSW:

rest.get('/api/user', (req, res, ctx) => {
  return res(ctx.json({ name: 'John Doe' }))
})

Pact:

const interaction = {
  state: 'a user exists',
  uponReceiving: 'a request for a user',
  withRequest: {
    method: 'GET',
    path: '/api/user'
  },
  willRespondWith: {
    status: 200,
    body: { name: 'John Doe' }
  }
}

Both MSW and Pact are powerful tools for API mocking and testing, but they serve different purposes. MSW focuses on request interception and mocking for frontend development and testing, while Pact specializes in contract testing between services. MSW offers a simpler setup and is more flexible for general mocking scenarios, whereas Pact provides robust contract generation and verification capabilities for microservices architectures.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

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)

NPM DownloadsLast 30 Days