msw 0.46.0 → 0.47.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,15 +5,12 @@
5
5
  </p>
6
6
 
7
7
  <h1 align="center">Mock Service Worker</h1>
8
- <p align="center">Mock Service Worker (MSW) is an API mocking library for browser and Node.js.</p>
8
+ <p align="center">Mock Service Worker (MSW) is a seamless REST/GraphQL API mocking library for browser and Node.js.</p>
9
9
 
10
10
  <p align="center">
11
11
  <a href="https://www.npmjs.com/package/msw" target="_blank">
12
12
  <img src="https://img.shields.io/npm/v/msw.svg?style=for-the-badge&label=Latest&color=black" alt="Package version" />
13
13
  </a>
14
- <a href="https://circleci.com/gh/mswjs/msw" target="_blank">
15
- <img src="https://img.shields.io/circleci/project/github/mswjs/msw/master.svg?style=for-the-badge&color=black" alt="Build status" />
16
- </a>
17
14
  <a href="https://www.npmjs.com/package/msw" target="_blank">
18
15
  <img src="https://img.shields.io/npm/dm/msw?style=for-the-badge&color=black" alt="Downloads per month" />
19
16
  </a>
@@ -27,8 +24,8 @@
27
24
  ## Features
28
25
 
29
26
  - **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.
30
- - **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.
31
- - **Familiar & Powerful**. Use [Express](https://github.com/expressjs/express)-like routing syntax to capture outgoing requests. Use parameters, wildcards, and regular expressions to match requests, and respond with necessary status codes, headers, cookies, delays, or completely custom resolvers.
27
+ - **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.
28
+ - **Familiar & Powerful**. Use [Express](https://github.com/expressjs/express)-like routing syntax to capture requests. Use parameters, wildcards, and regular expressions to match requests, and respond with necessary status codes, headers, cookies, delays, or completely custom resolvers.
32
29
 
33
30
  ---
34
31
 
@@ -38,6 +35,8 @@
38
35
 
39
36
  ## Documentation
40
37
 
38
+ 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.
39
+
41
40
  - [Documentation](https://mswjs.io/docs)
42
41
  - [**Getting started**](https://mswjs.io/docs/getting-started/install)
43
42
  - [Recipes](https://mswjs.io/docs/recipes)
@@ -54,27 +53,27 @@
54
53
 
55
54
  ### How does it work?
56
55
 
57
- Browser usage is what sets Mock Service Worker apart from other tools. Utilizing the [Service Worker API](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API), which can intercept requests for the purpose of caching, Mock Service Worker responds to captured requests with your mock definition on the network level. This way your application knows nothing about the mocking.
56
+ In-browser usage is what sets Mock Service Worker apart from other tools. Utilizing the [Service Worker API](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API), which can intercept requests for the purpose of caching, Mock Service Worker responds to captured requests with your mock definition on the network level. This way your application knows nothing about the mocking.
58
57
 
59
- **Watch a 30 seconds explanation on how Mock Service Worker works in a browser:**
58
+ **Take a look at this quick presentation on how Mock Service Worker functions in a browser:**
60
59
 
61
60
  [![What is Mock Service Worker?](https://raw.githubusercontent.com/mswjs/msw/main/media/msw-video-thumbnail.jpg)](https://youtu.be/HcQCqboatZk)
62
61
 
63
62
  ### How is it different?
64
63
 
65
- - Intercepts requests on the network level, not the application level.
66
- - If you think of your application as a box, Mock Service Worker lives in its own box next to yours, instead of opening and altering it for the purpose of mocking.
67
- - Agnostic of request-issuing libraries, so you can use it with `fetch`, `axios`, `react-query`, you-name-it.
68
- - The same mock definition can be reused for unit, integration, E2E testing, and debugging.
64
+ - 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;
65
+ - 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;
66
+ - No more stubbing of `fetch`, `axios`, `react-query`, you-name-it;
67
+ - 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.
69
68
 
70
69
  ### Usage example
71
70
 
72
71
  ```js
73
72
  // src/mocks.js
74
- // 1. Import mocking utils.
73
+ // 1. Import the library.
75
74
  import { setupWorker, rest } from 'msw'
76
75
 
77
- // 2. Define request handlers and response resolvers.
76
+ // 2. Describe network behavior with request handlers.
78
77
  const worker = setupWorker(
79
78
  rest.get('https://github.com/octocat', (req, res, ctx) => {
80
79
  return res(
@@ -87,7 +86,7 @@ const worker = setupWorker(
87
86
  }),
88
87
  )
89
88
 
90
- // 3. Start the Service Worker.
89
+ // 3. Start request interception by starting the Service Worker.
91
90
  worker.start()
92
91
  ```
93
92
 
@@ -95,103 +94,96 @@ Performing a `GET https://github.com/octocat` request in your application will r
95
94
 
96
95
  ![Chrome DevTools Network screenshot with the request mocked](https://github.com/mswjs/msw/blob/main/media/msw-quick-look-network.png?raw=true)
97
96
 
98
- > **Tip:** Did you know that although Service Worker runs in a separate thread, your mock definition executes on the client-side? That way you can use the same languages (i.e. TypeScript), third-party libraries, and internal logic in mocks.
97
+ > **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.
99
98
 
100
- ## Node
99
+ ## Node.js
101
100
 
102
101
  - [Learn more about using MSW in Node.js](https://mswjs.io/docs/getting-started/integrate/node)
103
102
  - [`setupServer` API](https://mswjs.io/docs/api/setup-server)
104
103
 
105
104
  ### How does it work?
106
105
 
107
- Although Service Worker is a browser-specific API, this library allows reusing of the same mock definition to have API mocking in Node.js through augmenting native request issuing modules.
106
+ There's no such thing as Service Workers in Node.js. Instead, MSW implements a [low-level interception algorithm](https://github.com/mswjs/interceptors) 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.
108
107
 
109
108
  ### How is it different?
110
109
 
111
- - Prevents from stubbing `fetch`/`axios`/etc. as a part of your test, allowing you to treat API mocking as a pre-requisite and focus on what actually matters during testing.
112
- - The same mock definition you use for local development can be reused for testing.
110
+ - Does not stub `fetch`, `axios`, etc. As a result, your tests know _nothing_ about mocking;
111
+ - 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.
113
112
 
114
113
  ### Usage example
115
114
 
116
- Here's an example of an actual integration test in Jest that uses [React Testing Library](https://github.com/testing-library/react-testing-library) and Mock Service Worker:
115
+ Take a look at the example of an integration test in Jest that uses [React Testing Library](https://github.com/testing-library/react-testing-library) and Mock Service Worker:
117
116
 
118
117
  ```js
119
- // test/LoginForm.test.js
120
- import '@testing-library/jest-dom'
118
+ // test/Dashboard.test.js
119
+
121
120
  import React from 'react'
122
121
  import { rest } from 'msw'
123
122
  import { setupServer } from 'msw/node'
124
- import { render, screen } from '@testing-library/react'
125
- import userEvent from '@testing-library/user-event'
126
- import Login from '../src/components/Login'
123
+ import { render, screen, waitFor } from '@testing-library/react'
124
+ import Dashboard from '../src/components/Dashboard'
127
125
 
128
126
  const server = setupServer(
129
- rest.post('/login', (req, res, ctx) => {
130
- // Respond with a mocked user token that gets persisted
131
- // in the `sessionStorage` by the `Login` component.
132
- return res(ctx.json({ token: 'mocked_user_token' }))
127
+ // Describe network behavior with request handlers.
128
+ // Tip: move the handlers into their own module and
129
+ // import it across your browser and Node.js setups!
130
+ rest.get('/posts', (req, res, ctx) => {
131
+ return res(
132
+ ctx.json([
133
+ {
134
+ id: 'f8dd058f-9006-4174-8d49-e3086bc39c21',
135
+ title: `Avoid Nesting When You're Testing`,
136
+ },
137
+ {
138
+ id: '8ac96078-6434-4959-80ed-cc834e7fef61',
139
+ title: `How I Built A Modern Website In 2021`,
140
+ },
141
+ ]),
142
+ )
133
143
  }),
134
144
  )
135
145
 
136
- // Enable API mocking before tests.
146
+ // Enable request interception.
137
147
  beforeAll(() => server.listen())
138
148
 
139
- // Reset any runtime request handlers we may add during the tests.
149
+ // Reset handlers so that each test could alter them
150
+ // without affecting other, unrelated tests.
140
151
  afterEach(() => server.resetHandlers())
141
152
 
142
- // Disable API mocking after the tests are done.
153
+ // Don't forget to clean up afterwards.
143
154
  afterAll(() => server.close())
144
155
 
145
- test('allows the user to log in', async () => {
146
- render(<Login />)
147
- userEvent.type(
148
- screen.getByRole('textbox', { name: /username/i }),
149
- 'john.maverick',
150
- )
151
- userEvent.type(
152
- screen.getByRole('textbox', { name: /password/i }),
153
- 'super-secret',
154
- )
155
- userEvent.click(screen.getByText(/submit/i))
156
- const alert = await screen.findByRole('alert')
157
-
158
- // Assert successful login state
159
- expect(alert).toHaveTextContent(/welcome/i)
160
- expect(window.sessionStorage.getItem('token')).toEqual(fakeUserResponse.token)
161
- })
156
+ it('displays the list of recent posts', async () => {
157
+ render(<Dashboard />)
162
158
 
163
- test('handles login exception', () => {
164
- server.use(
165
- rest.post('/login', (req, res, ctx) => {
166
- // Respond with "500 Internal Server Error" status for this test.
167
- return res(
168
- ctx.status(500),
169
- ctx.json({ message: 'Internal Server Error' }),
170
- )
171
- }),
172
- )
173
-
174
- render(<Login />)
175
- userEvent.type(
176
- screen.getByRole('textbox', { name: /username/i }),
177
- 'john.maverick',
178
- )
179
- userEvent.type(
180
- screen.getByRole('textbox', { name: /password/i }),
181
- 'super-secret',
182
- )
183
- userEvent.click(screen.getByText(/submit/i))
184
-
185
- // Assert meaningful error message shown to the user
186
- expect(alert).toHaveTextContent(/sorry, something went wrong/i)
187
- expect(window.sessionStorage.getItem('token')).toBeNull()
159
+ // 🕗 Wait for the posts request to be finished.
160
+ await waitFor(() => {
161
+ expect(
162
+ screen.getByLabelText('Fetching latest posts...'),
163
+ ).not.toBeInTheDocument()
164
+ })
165
+
166
+ // ✅ Assert that the correct posts have loaded.
167
+ expect(
168
+ screen.getByRole('link', { name: /Avoid Nesting When You're Testing/ }),
169
+ ).toBeVisible()
170
+
171
+ expect(
172
+ screen.getByRole('link', { name: /How I Built A Modern Website In 2021/ }),
173
+ ).toBeVisible()
188
174
  })
189
175
  ```
190
176
 
191
- > **Tip:** Did you know that although the API is called `setupServer`, there are no actual servers involved? The name is chosen for familiarity, and the API is designed to resemble operating with an actual server.
177
+ > Don't get overwhelmed! We've prepared a step-by-step [**Getting started**](https://mswjs.io/docs/getting-started/install) tutorial that you can follow to learn how to integrate Mock Service Worker into your project.
178
+
179
+ 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.
192
180
 
193
181
  ## Sponsors
194
182
 
183
+ 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.
184
+
185
+ **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!
186
+
195
187
  ### Golden Sponsors
196
188
 
197
189
  > Become our first golden sponsor and get featured right here, enjoying other perks like issue prioritization and a personal consulting session with us.
@@ -227,6 +219,8 @@ test('handles login exception', () => {
227
219
 
228
220
  ## Awards & Mentions
229
221
 
222
+ 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.
223
+
230
224
  <table>
231
225
  <tr valign="middle">
232
226
  <td width="124">
@@ -253,7 +253,7 @@ declare abstract class RequestHandler<HandlerInfo extends RequestHandlerDefaultI
253
253
  /**
254
254
  * Print out the successfully handled request.
255
255
  */
256
- abstract log(request: Request, response: SerializedResponse<any>, handler: this, parsedResult: ParsedResult): void;
256
+ abstract log(request: Request, response: SerializedResponse<any>, parsedResult: ParsedResult): void;
257
257
  /**
258
258
  * Parse the captured request to extract additional information from it.
259
259
  * Parsed result is then exposed to other methods of this request handler.