Skip to content

Commit 1e246f8

Browse files
docs: use msw/browser in component testing examples (#8909)
Co-authored-by: Vladimir <sleuths.slews0s@icloud.com>
1 parent a06d122 commit 1e246f8

1 file changed

Lines changed: 14 additions & 13 deletions

File tree

docs/guide/browser/component-testing.md

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -261,23 +261,20 @@ test('ShoppingCart manages items correctly', async () => {
261261
```tsx
262262
// Option 1: Recommended - Use MSW (Mock Service Worker) for API mocking
263263
import { http, HttpResponse } from 'msw'
264-
import { setupServer } from 'msw/node'
264+
import { setupWorker } from 'msw/browser'
265265

266-
// Set up MSW server with API handlers
267-
const server = setupServer(
266+
// Set up MSW worker with API handlers
267+
const worker = setupWorker(
268268
http.get('/api/users/:id', ({ params }) => {
269-
const { id } = params
270-
if (id === '123') {
271-
return HttpResponse.json({ name: 'John Doe', email: 'john@example.com' })
272-
}
273-
return HttpResponse.json({ error: 'User not found' }, { status: 404 })
269+
// Describe the happy path
270+
return HttpResponse.json({ id: params.id, name: 'John Doe', email: 'john@example.com' })
274271
})
275272
)
276273

277-
// Start server before all tests
278-
beforeAll(() => server.listen())
279-
afterEach(() => server.resetHandlers())
280-
afterAll(() => server.close())
274+
// Start the worker before all tests
275+
beforeAll(() => worker.start())
276+
afterEach(() => worker.resetHandlers())
277+
afterAll(() => worker.stop())
281278

282279
test('UserProfile handles loading, success, and error states', async () => {
283280
// Test success state
@@ -287,7 +284,7 @@ test('UserProfile handles loading, success, and error states', async () => {
287284
await expect.element(getByText('john@example.com')).toBeInTheDocument()
288285

289286
// Test error state by overriding the handler for this test
290-
server.use(
287+
worker.use(
291288
http.get('/api/users/:id', () => {
292289
return HttpResponse.json({ error: 'User not found' }, { status: 404 })
293290
})
@@ -298,6 +295,10 @@ test('UserProfile handles loading, success, and error states', async () => {
298295
})
299296
```
300297

298+
::: tip
299+
See more details on [using MSW in the browser](https://mswjs.io/docs/integrations/browser).
300+
:::
301+
301302
### Testing Component Communication
302303

303304
```tsx

0 commit comments

Comments
 (0)