Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
The msw (Mock Service Worker) npm package is a tool for mocking network requests at the service worker level. It allows developers to intercept and modify any outgoing HTTP requests from their application, which is useful for testing, development, and debugging purposes. It can be used in both browser and Node.js environments.
Mocking REST API requests
This feature allows you to intercept and mock responses to REST API requests. The code sample demonstrates how to set up a mock server that responds to a GET request to '/user' with a JSON object containing a username.
import { rest } from 'msw';
import { setupServer } from 'msw/node';
const server = setupServer(
rest.get('/user', (req, res, ctx) => {
return res(ctx.status(200), ctx.json({ username: 'admin' }));
})
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
Mocking GraphQL API requests
This feature enables the mocking of GraphQL API requests. The code sample shows how to create a mock server that handles a GraphQL query named 'GetUser' and returns a response with user data.
import { graphql } from 'msw';
import { setupServer } from 'msw/node';
const server = setupServer(
graphql.query('GetUser', (req, res, ctx) => {
return res(ctx.data({ user: { id: '1', name: 'John Doe' } }));
})
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
Delaying mocked responses
This feature allows you to simulate network delays in your mocked responses. The code sample sets up a mock server that delays the response to a GET request to '/user' by 1500 milliseconds.
import { rest } from 'msw';
import { setupServer } from 'msw/node';
const server = setupServer(
rest.get('/user', (req, res, ctx) => {
return res(ctx.delay(1500), ctx.json({ username: 'admin' }));
})
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
Nock is a popular HTTP server mocking and expectations library for Node.js. It allows you to intercept HTTP requests and provide predefined responses. Unlike msw, which works with service workers and can be used in both browser and Node.js environments, nock is designed specifically for Node.js.
axios-mock-adapter is a library for mocking Axios requests. It provides a way to mock requests made using the Axios library, allowing you to specify the expected response for a given request. This package is more specific to Axios, while msw is agnostic to the HTTP client used.
jest-fetch-mock is a package that provides a way to easily mock fetch requests when using Jest. It's specifically tailored for Jest users and is used to mock the global fetch function. msw, on the other hand, intercepts requests at a lower level and is not limited to Jest or fetch.
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."
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;// 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:
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:
// 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.
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) |
FAQs
Seamless REST/GraphQL API mocking library for browser and Node.js.
We found that msw demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.