Installations
npm install msw
Developer
Developer Guide
Module System
CommonJS, ESM
Min. Node Version
>=18
Typescript Support
Yes
Node Version
18.20.5
NPM Version
10.8.2
Statistics
16,003 Stars
1,581 Commits
525 Forks
63 Watching
21 Branches
159 Contributors
Updated on 27 Nov 2024
Languages
TypeScript (96%)
JavaScript (3.59%)
HTML (0.3%)
Shell (0.11%)
Total Downloads
Cumulative downloads
Total Downloads
345,794,564
Last day
-0.9%
803,549
Compared to previous day
Last week
5%
4,133,800
Compared to previous week
Last month
14.7%
17,128,942
Compared to previous month
Last year
37%
155,087,380
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
18
Peer Dependencies
1
Dev Dependencies
47
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 Service Worker
Mock Service Worker (MSW) is a seamless REST/GraphQL API mocking library for browser and Node.js.
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
- See the list of Usage 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:
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
1// src/mocks.js 2// 1. Import the library. 3import { http, HttpResponse } from 'msw' 4import { setupWorker } from 'msw/browser' 5 6// 2. Describe network behavior with request handlers. 7const worker = setupWorker( 8 http.get('https://github.com/octocat', ({ request, params, cookies }) => { 9 return HttpResponse.json( 10 { 11 message: 'Mocked response', 12 }, 13 { 14 status: 202, 15 statusText: 'Mocked status', 16 }, 17 ) 18 }), 19) 20 21// 3. Start request interception by starting the Service Worker. 22await 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:
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:
1// test/Dashboard.test.js
2
3import React from 'react'
4import { http, HttpResponse } from 'msw'
5import { setupServer } from 'msw/node'
6import { render, screen, waitFor } from '@testing-library/react'
7import Dashboard from '../src/components/Dashboard'
8
9const server = setupServer(
10 // Describe network behavior with request handlers.
11 // Tip: move the handlers into their own module and
12 // import it across your browser and Node.js setups!
13 http.get('/posts', ({ request, params, cookies }) => {
14 return HttpResponse.json([
15 {
16 id: 'f8dd058f-9006-4174-8d49-e3086bc39c21',
17 title: `Avoid Nesting When You're Testing`,
18 },
19 {
20 id: '8ac96078-6434-4959-80ed-cc834e7fef61',
21 title: `How I Built A Modern Website In 2021`,
22 },
23 ])
24 }),
25)
26
27// Enable request interception.
28beforeAll(() => server.listen())
29
30// Reset handlers so that each test could alter them
31// without affecting other, unrelated tests.
32afterEach(() => server.resetHandlers())
33
34// Don't forget to clean up afterwards.
35afterAll(() => server.close())
36
37it('displays the list of recent posts', async () => {
38 render(<Dashboard />)
39
40 // 🕗 Wait for the posts request to be finished.
41 await waitFor(() => {
42 expect(
43 screen.getByLabelText('Fetching latest posts...'),
44 ).not.toBeInTheDocument()
45 })
46
47 // ✅ Assert that the correct posts have loaded.
48 expect(
49 screen.getByRole('link', { name: /Avoid Nesting When You're Testing/ }),
50 ).toBeVisible()
51
52 expect(
53 screen.getByRole('link', { name: /How I Built A Modern Website In 2021/ }),
54 ).toBeVisible()
55})
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.
Silver Sponsors
Become our silver sponsor and get your profile image and link featured right here.
Learn more on our GitHub Sponsors profile.
Bronze Sponsors
Become our bronze sponsor and get your profile image and link featured in this section.
Learn more on our GitHub Sponsors profile.
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.
Solution Worth PursuingTechnology Radar (2020–2021) | |
The Most Exciting Use of TechnologyOpen Source Awards (2020) |
No vulnerabilities found.
Reason
30 commit(s) and 5 issue activity found in the last 90 days -- score normalized to 10
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE.md:0
- Info: FSF or OSI recognized license: MIT License: LICENSE.md:0
Reason
Found 7/30 approved changesets -- score normalized to 2
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Info: jobLevel 'contents' permission set to 'read': .github/workflows/release.yml:12
- Warn: no topLevel permission defined: .github/workflows/auto.yml:1
- Warn: no topLevel permission defined: .github/workflows/ci.yml:1
- Warn: no topLevel permission defined: .github/workflows/compat.yml:1
- Warn: no topLevel permission defined: .github/workflows/release-preview.yml:1
- Warn: no topLevel permission defined: .github/workflows/release.yml:1
- Warn: no topLevel permission defined: .github/workflows/smoke-test.yml:1
- Warn: no topLevel permission defined: .github/workflows/typescript-nightly.yml:1
- Info: no jobLevel write permissions found
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Info: Possibly incomplete results: error parsing shell code: invalid parameter name: .github/workflows/typescript-nightly.yml:62
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/auto.yml:10: update your workflow using https://app.stepsecurity.io/secureworkflow/mswjs/msw/auto.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:17: update your workflow using https://app.stepsecurity.io/secureworkflow/mswjs/msw/ci.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:20: update your workflow using https://app.stepsecurity.io/secureworkflow/mswjs/msw/ci.yml/main?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/ci.yml:24: update your workflow using https://app.stepsecurity.io/secureworkflow/mswjs/msw/ci.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:54: update your workflow using https://app.stepsecurity.io/secureworkflow/mswjs/msw/ci.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/compat.yml:15: update your workflow using https://app.stepsecurity.io/secureworkflow/mswjs/msw/compat.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/compat.yml:18: update your workflow using https://app.stepsecurity.io/secureworkflow/mswjs/msw/compat.yml/main?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/compat.yml:23: update your workflow using https://app.stepsecurity.io/secureworkflow/mswjs/msw/compat.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/compat.yml:60: update your workflow using https://app.stepsecurity.io/secureworkflow/mswjs/msw/compat.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/compat.yml:63: update your workflow using https://app.stepsecurity.io/secureworkflow/mswjs/msw/compat.yml/main?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/compat.yml:67: update your workflow using https://app.stepsecurity.io/secureworkflow/mswjs/msw/compat.yml/main?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/lock-closed-issues.yml:14: update your workflow using https://app.stepsecurity.io/secureworkflow/mswjs/msw/lock-closed-issues.yml/main?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/release-preview.yml:20: update your workflow using https://app.stepsecurity.io/secureworkflow/mswjs/msw/release-preview.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/release-preview.yml:32: update your workflow using https://app.stepsecurity.io/secureworkflow/mswjs/msw/release-preview.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/release-preview.yml:35: update your workflow using https://app.stepsecurity.io/secureworkflow/mswjs/msw/release-preview.yml/main?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/release-preview.yml:40: update your workflow using https://app.stepsecurity.io/secureworkflow/mswjs/msw/release-preview.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/release.yml:16: update your workflow using https://app.stepsecurity.io/secureworkflow/mswjs/msw/release.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/release.yml:22: update your workflow using https://app.stepsecurity.io/secureworkflow/mswjs/msw/release.yml/main?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/release.yml:29: update your workflow using https://app.stepsecurity.io/secureworkflow/mswjs/msw/release.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/smoke-test.yml:18: update your workflow using https://app.stepsecurity.io/secureworkflow/mswjs/msw/smoke-test.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/smoke-test.yml:21: update your workflow using https://app.stepsecurity.io/secureworkflow/mswjs/msw/smoke-test.yml/main?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/smoke-test.yml:26: update your workflow using https://app.stepsecurity.io/secureworkflow/mswjs/msw/smoke-test.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/typescript-nightly.yml:14: update your workflow using https://app.stepsecurity.io/secureworkflow/mswjs/msw/typescript-nightly.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/typescript-nightly.yml:40: update your workflow using https://app.stepsecurity.io/secureworkflow/mswjs/msw/typescript-nightly.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/typescript-nightly.yml:43: update your workflow using https://app.stepsecurity.io/secureworkflow/mswjs/msw/typescript-nightly.yml/main?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/typescript-nightly.yml:48: update your workflow using https://app.stepsecurity.io/secureworkflow/mswjs/msw/typescript-nightly.yml/main?enable=pin
- Info: 0 out of 16 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 10 third-party GitHubAction dependencies pinned
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 16 are checked with a SAST tool
Reason
12 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-28mc-g557-92m7
- Warn: Project is vulnerable to: GHSA-qwcr-r2fm-qrc7
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-pxg6-pf52-xh8x
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-qw6h-vgh9-j6wx
- Warn: Project is vulnerable to: GHSA-9wv6-86v2-598j
- Warn: Project is vulnerable to: GHSA-gcx4-mw62-g8wm
- Warn: Project is vulnerable to: GHSA-m6fv-jmcg-4jfg
- Warn: Project is vulnerable to: GHSA-cm22-4g7w-348p
- Warn: Project is vulnerable to: GHSA-3h5v-q93c-6h6q
- Warn: Project is vulnerable to: GHSA-p9pc-299p-vxgp
Score
4
/10
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More