Skip to content

Commit

Permalink
docs: update readme (#2441)
Browse files Browse the repository at this point in the history
  • Loading branch information
kettanaito authored Feb 24, 2025
1 parent fd77dbb commit b7d9ce4
Showing 1 changed file with 44 additions and 77 deletions.
121 changes: 44 additions & 77 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,7 @@
> **MSW 2.0 is finally here! 🎉** Read the [Release notes](https://github.com/mswjs/msw/releases/tag/v2.0.0) and please follow the [**Migration guidelines**](https://mswjs.io/docs/migrations/1.x-to-2.x) to upgrade. If you're having any questions while upgrading, please reach out in our [Discord server](https://kettanaito.com/discord).
>
> We've also recorded the most comprehensive introduction to MSW ever. Learn how to mock APIs like a pro in our official video course:
<a href="https://egghead.io/courses/mock-rest-and-graphql-apis-with-mock-service-worker-8d471ece?af=8mci9b" target="_blank">
<img src="media/egghead-banner.png" alt="Mock REST and GraphQL APIs with Mock Service Worker" />
</a>

<br />
<br />

<p align="center">
<img src="media/msw-logo.svg" width="100" alt="Mock Service Worker logo" />
<img src="media/msw-logo.svg" width="100" alt="The Mock Service Worker logo" />
</p>

<h1 align="center">Mock Service Worker</h1>
Expand All @@ -23,7 +14,6 @@
</p>

<br />

<br />

## Features
Expand All @@ -36,11 +26,11 @@

> "_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](https://twitter.com/kentcdodds)
> [Kent C. Dodds](https://twitter.com/kentcdodds)
## 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.
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.

- [Documentation](https://mswjs.io/docs)
- [**Getting started**](https://mswjs.io/docs/getting-started)
Expand All @@ -50,6 +40,13 @@ This README will give you a brief overview on the library but there's no better

- See the list of [**Usage examples**](https://github.com/mswjs/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.

- 🚀 [**Mocking REST and GraphQL APIs with Mock Service Worker**](https://egghead.io/courses/mock-rest-and-graphql-apis-with-mock-service-worker-8d471ece?af=8mci9b)
- 🔌 [Mocking (and testing) WebSocket APIs with Mock Service Worker](https://egghead.io/courses/mocking-websocket-apis-with-mock-service-worker-9933b7f5)

## Browser

- [Learn more about using MSW in a browser](https://mswjs.io/docs/integrations/browser)
Expand All @@ -68,12 +65,11 @@ In-browser usage is what sets Mock Service Worker apart from other tools. Utiliz
- 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.
- 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

```js
// src/mocks.js
// 1. Import the library.
import { http, HttpResponse } from 'msw'
import { setupWorker } from 'msw/browser'
Expand All @@ -93,15 +89,15 @@ const worker = setupWorker(
}),
)

// 3. Start request interception by starting the Service Worker.
// 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](https://github.com/mswjs/msw/blob/main/media/msw-quick-look-network.png?raw=true)

> **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.
> **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

Expand All @@ -119,77 +115,48 @@ There's no such thing as Service Workers in Node.js. Instead, MSW implements a [

### Usage example

Take a look at the example of an integration test in Vitest that uses [React Testing Library](https://github.com/testing-library/react-testing-library) and Mock Service Worker:
Here's an example of using Mock Service Worker while developing your Express server:

```js
// test/Dashboard.test.js

import React from 'react'
import express from 'express'
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()
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',
})
},
),
)

expect(
screen.getByRole('link', { name: /How I Built A Modern Website In 2021/ }),
).toBeVisible()
})
// Continue with processing the checkout session.
handleSession(req, res)
}),
)
```

> Don't get overwhelmed! We've prepared a step-by-step [**Getting started**](https://mswjs.io/docs/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.
> This example showcases [`server.boundary()`](https://mswjs.io/docs/api/setup-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, 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.
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](https://github.com/sponsors/mswjs) 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
### Golden sponsors

> Become our _golden sponsor_ and get featured right here, enjoying other perks like issue prioritization and a personal consulting session with us.
>
Expand Down Expand Up @@ -232,7 +199,7 @@ Mock Service Worker is trusted by hundreds of thousands of engineers around the
</tr>
</table>

### Silver Sponsors
### Silver sponsors

> Become our _silver sponsor_ and get your profile image and link featured right here.
>
Expand Down Expand Up @@ -260,7 +227,7 @@ Mock Service Worker is trusted by hundreds of thousands of engineers around the
</tr>
</table>

### Bronze Sponsors
### Bronze sponsors

> Become our _bronze sponsor_ and get your profile image and link featured in this section.
>
Expand Down Expand Up @@ -288,7 +255,7 @@ Mock Service Worker is trusted by hundreds of thousands of engineers around the
</tr>
</table>

## Awards & Mentions
## 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.

Expand Down

0 comments on commit b7d9ce4

Please sign in to comment.