Skip to content

Commit f11d491

Browse files
committed
update msw and simplify test/dev setups
1 parent 7919c51 commit f11d491

File tree

27 files changed

+103
-144
lines changed

27 files changed

+103
-144
lines changed

exercises/03.best-practices/03.problem.network-mocking/README.mdx

Lines changed: 29 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -51,27 +51,9 @@ import { setupWorker } from 'msw/browser'
5151
import { handlers } from './handlers.js'
5252

5353
export const worker = setupWorker(...handlers)
54-
55-
export async function startWorker() {
56-
await worker.start({
57-
quiet: true,
58-
onUnhandledRequest(request, print) {
59-
if (/(\.(css|tsx?|woff2?))/.test(request.url)) {
60-
return
61-
}
62-
63-
print.error()
64-
},
65-
})
66-
}
6754
```
6855

69-
Let's briefly go over what's happening here:
70-
71-
- The `setupWorker()` function prepares a Service Worker instance configured with the given request `handlers`. Note that it _doesn't start it_ just yet!
72-
- The `startWorker()` function abstracts starting the worker so we can potentially reuse it in multiple places.
73-
- `quiet: true` disables MSW logging to keep our consoles clean.
74-
- `onUnhandledRequest` decides how to handle requests that you don't have mocks for. In this case, we are ignoring any asset requests while reacting to any other unhandled requests with an error.
56+
> The `setupWorker()` function prepares a Service Worker instance configured with the given request `handlers`. Note that it _doesn't start_ the request interception just yet!
7557
7658
After this step, you would normally introduce the `enableMocking()` function and wrap it around your application's initialization. With Vitest Browser Mode, the root of your app (`main.tsx`) doesn't run in tests so you need to start MSW differently.
7759

@@ -85,11 +67,15 @@ Since it's a new TypeScript module, you need to tell TypeScript how to handle it
8567

8668
🐨 In <InlineFile file="tsconfig.test.browser.json">`tsconfig.test.browser.json`</InlineFile>, add `"test-extend.ts"` to the `include` array:
8769

88-
```json filename=tsconfig.test.browser.json remove=3 add=4
70+
```json filename=tsconfig.test.browser.json remove=3 add=4-8 highlight=7
8971
{
9072
"extends": "./tsconfig.base.json",
91-
"include": ["**/*.browser.test.ts*"],
92-
"include": ["**/*.browser.test.ts*", "test-extend.ts"],
73+
"include": ["vitest.browser.setup.ts", "**/*.browser.test.ts*"],
74+
"include": [
75+
"vitest.browser.setup.ts",
76+
"**/*.browser.test.ts*",
77+
"test-extend.ts"
78+
],
9379
"compilerOptions": {
9480
"target": "esnext",
9581
"module": "preserve",
@@ -130,14 +116,17 @@ Right now, the `worker` property has an array of two elements: `fixture` and `op
130116

131117
🐨 Provide the following fixture for the `worker`:
132118

133-
```ts filename=test-extend.ts add=2,6-10
119+
```ts filename=test-extend.ts add=2,6-13
134120
import { test as testBase } from 'vitest'
135-
import { startWorker, worker } from './src/mocks/browser.js'
121+
import { worker } from './src/mocks/browser.js'
136122

137123
export const test = testBase.extend({
138124
worker: [
139125
async ({}, use) => {
140-
await startWorker()
126+
await worker.start({
127+
quiet: true,
128+
onUnhandledRequest: 'error',
129+
})
141130
await use(worker)
142131
worker.stop()
143132
},
@@ -146,7 +135,9 @@ export const test = testBase.extend({
146135
})
147136
```
148137

149-
In this fixture, you are telling Vitest to start the worker (`await startWorker()` from `src/mocks/browser.js` you've prepared earlier), then expose it to the test (`await use(worker)`), and finally call `worker.stop()` after the test is done.
138+
In this fixture, you are staring the MSW'w worker by calling `await worker.start()`. Here, you're providing `quiet: true` to disable MSW logging intercepted requests in the console during the test run to have a less noisy output, and also the `onUnhandledRequest: 'error'` option so the library errors if there are any requests in tests that you haven't handled.
139+
140+
Then, you expose that `worker` reference so it can be accessed in tests (the `await use(worker)` part). And, finally, `worker.stop()` stops the mocking after the test has finished.
150141

151142
🐨 To help Vitest understand the types of this `worker` fixture, annotate it explicitly by creating a new type called `TestContext`, describing the worker there, and providing it as a type argument to `test.extend()`:
152143

@@ -174,14 +165,21 @@ You want MSW up and running _in every test_ so you can take advantage of its req
174165
175166
🐨 To do that, configure the `worker` fixture to have the `auto: true` option:
176167
177-
```ts filename=test-extend.ts add=11
168+
```ts filename=test-extend.ts add=18
178169
import { test as testBase } from 'vitest'
179-
import { startWorker, worker } from './src/mocks/browser.js'
170+
import { worker } from './src/mocks/browser.js'
180171

181-
export const test = testBase.extend({
172+
type TestContext = {
173+
worker: typeof worker
174+
}
175+
176+
export const test = testBase.extend<TestContext>({
182177
worker: [
183178
async ({}, use) => {
184-
await startWorker()
179+
await worker.start({
180+
quiet: true,
181+
onUnhandledRequest: 'error',
182+
})
185183
await use(worker)
186184
worker.stop()
187185
},
@@ -218,7 +216,7 @@ This request handler will intercept any matching requests and execute the callba
218216

219217
Our component expects a response from the server to have the following shape:
220218

221-
```ts
219+
```ts nonumber
222220
{
223221
code: string
224222
amount: number

exercises/03.best-practices/03.solution.network-mocking/README.mdx

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -108,8 +108,8 @@ import { App } from './app.jsx'
108108

109109
async function enableMocking() {
110110
if (process.env.NODE_ENV === 'development') {
111-
const { startWorker } = await import('./mocks/browser.js')
112-
await startWorker()
111+
const { worker } = await import('./mocks/browser.js')
112+
await worker.start()
113113
}
114114
}
115115

@@ -127,7 +127,7 @@ enableMocking().then(() => {
127127
This functions does a couple of things:
128128
129129
1. Imports the `./mocks/browser.js` module _conditionally_ to enable MSW only in development;
130-
1. Calls the `startWorker()` function to actually register and start the Service Worker. This is the same function you've used in `test-extend.ts`!
130+
1. Calls `await worker.start()` to actually register and start the Service Worker.
131131
132132
## Related materials
133133

exercises/03.best-practices/03.solution.network-mocking/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
"@types/react-dom": "^19.0.3",
1717
"@vitejs/plugin-react": "^4.3.4",
1818
"@vitest/browser": "^3.0.5",
19-
"msw": "^2.7.2",
19+
"msw": "^2.7.3",
2020
"playwright": "^1.49.1",
2121
"tailwindcss": "^4.0.7",
2222
"vite": "^6.0.7",

exercises/03.best-practices/03.solution.network-mocking/src/main.tsx

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,11 @@ import { App } from './app.jsx'
55

66
async function enableMocking() {
77
if (process.env.NODE_ENV === 'development') {
8-
const { startWorker } = await import('./mocks/browser.js')
9-
await startWorker()
8+
const { worker } = await import('./mocks/browser.js')
9+
10+
await worker.start({
11+
onUnhandledRequest: 'warn',
12+
})
1013
}
1114
}
1215

exercises/03.best-practices/03.solution.network-mocking/src/mocks/browser.ts

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,3 @@ import { setupWorker } from 'msw/browser'
22
import { handlers } from './handlers.js'
33

44
export const worker = setupWorker(...handlers)
5-
6-
export async function startWorker() {
7-
await worker.start({
8-
quiet: true,
9-
onUnhandledRequest(request, print) {
10-
if (/(\.(css|tsx?|woff2?))/.test(request.url)) {
11-
return
12-
}
13-
14-
print.error()
15-
},
16-
})
17-
}

exercises/03.best-practices/03.solution.network-mocking/test-extend.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { test as testBase } from 'vitest'
2-
import { startWorker, worker } from './src/mocks/browser.js'
2+
import { worker } from './src/mocks/browser.js'
33

44
type TestContext = {
55
worker: typeof worker
@@ -8,7 +8,10 @@ type TestContext = {
88
export const test = testBase.extend<TestContext>({
99
worker: [
1010
async ({}, use) => {
11-
await startWorker()
11+
await worker.start({
12+
quiet: true,
13+
onUnhandledRequest: 'error',
14+
})
1215
await use(worker)
1316
worker.stop()
1417
},

exercises/03.best-practices/04.problem.element-presence/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
"@types/react-dom": "^19.0.3",
1717
"@vitejs/plugin-react": "^4.3.4",
1818
"@vitest/browser": "^3.0.5",
19-
"msw": "^2.7.2",
19+
"msw": "^2.7.3",
2020
"playwright": "^1.49.1",
2121
"tailwindcss": "^4.0.7",
2222
"vite": "^6.0.7",

exercises/03.best-practices/04.problem.element-presence/src/main.tsx

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,10 @@ import { App } from './app.jsx'
55

66
async function enableMocking() {
77
if (process.env.NODE_ENV === 'development') {
8-
const { startWorker } = await import('./mocks/browser.js')
9-
await startWorker()
8+
const { worker } = await import('./mocks/browser.js')
9+
await worker.start()
1010
}
1111
}
12-
1312
enableMocking().then(() => {
1413
createRoot(document.getElementById('root')!).render(
1514
<StrictMode>

exercises/03.best-practices/04.problem.element-presence/src/mocks/browser.ts

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,3 @@ import { setupWorker } from 'msw/browser'
22
import { handlers } from './handlers.js'
33

44
export const worker = setupWorker(...handlers)
5-
6-
export async function startWorker() {
7-
await worker.start({
8-
quiet: true,
9-
onUnhandledRequest(request, print) {
10-
if (/(\.(css|tsx?|woff2?))/.test(request.url)) {
11-
return
12-
}
13-
14-
print.error()
15-
},
16-
})
17-
}

exercises/03.best-practices/04.problem.element-presence/test-extend.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { test as testBase } from 'vitest'
2-
import { startWorker, worker } from './src/mocks/browser.js'
2+
import { worker } from './src/mocks/browser.js'
33

44
type TestContext = {
55
worker: typeof worker
@@ -8,8 +8,10 @@ type TestContext = {
88
export const test = testBase.extend<TestContext>({
99
worker: [
1010
async ({}, use) => {
11-
await startWorker()
12-
worker.resetHandlers()
11+
await worker.start({
12+
quiet: true,
13+
onUnhandledRequest: 'error',
14+
})
1315
await use(worker)
1416
worker.stop()
1517
},

0 commit comments

Comments
 (0)