Gathering detailed insights and metrics for msw
Gathering detailed insights and metrics for msw
Gathering detailed insights and metrics for msw
Gathering detailed insights and metrics for msw
npm install msw
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
16,003 Stars
1,581 Commits
525 Forks
63 Watching
21 Branches
159 Contributors
Updated on 27 Nov 2024
TypeScript (96%)
JavaScript (3.59%)
HTML (0.3%)
Shell (0.11%)
Cumulative downloads
Total Downloads
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
18
1
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 (MSW) is a seamless REST/GraphQL API mocking library for browser and Node.js.
"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
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.
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:
fetch
, axios
, react-query
, you-name-it;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.
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.
fetch
, axios
, etc. As a result, your tests know nothing about mocking;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.
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!
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.
Become our silver sponsor and get your profile image and link featured right here.
Learn more on our GitHub Sponsors profile.
Become our bronze sponsor and get your profile image and link featured in this section.
Learn more on our GitHub Sponsors profile.
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
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
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
project is not fuzzed
Details
Reason
security policy file not detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
12 existing vulnerabilities detected
Details
Score
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