LOGOMock Service Worker
  1. Api
  2. setupServer()
  3. resetHandlers()

resetHandlers()

Removes any request handlers that were added on runtime (after the initial setupServer call).

This function accepts an optional list of request handlers to override the initial handlers to re-declare the mock definition completely on runtime.

Examples

Default behavior

The .resetHandlers() function is useful as a clean up mechanism between multiple test suites that leverage runtime request handlers.

1import { rest } from 'msw'
2import { setupServer } from 'msw/node'
3
4const server = setupServer(
5 rest.get('/book/:bookId', (req, res, ctx) => {
6 return res(ctx.json({ title: 'Lord of the Rings' }))
7 }),
8)
9
10beforeAll(() => {
11 server.listen()
12})
13
14afterEach(() => {
15 server.resetHandlers()
16})
17
18afterAll(() => {
19 server.close()
20})
21
22test('adds new book review', () => {
23 server.use(
24 // Adds a runtime request handler for posting a new book review.
25 rest.post('/book/:bookId/reviews', bookReviewResolver),
26 )
27
28 // Performing a "POST /book/:bookId/reviews" request
29 // will get the mocked response from `bookReviewResolver`.
30})
31
32test('asserts another scenario', () => {
33 // Since we call `server.resetHandlers()` after each test,
34 // this test suite will know nothing about "POST /book/:bookId/reviews".
35})

Replacing initial handlers

When provided a list of request handlers, .resetHandlers() will additionally replace any initial request handlers with the explicitly provided ones.

1const server = setupServer(rest.get('/book/:bookId', bookDetailResolver))
2
3test('first test', () => {
4 // Can handle "GET /book/:bookId".
5})
6
7test('second test', () => {
8 server.resetHandlers(rest.post('/login', loginResolver))
9
10 // This, and any subsequent tests, will NOT handle
11 // "GET /book/:bookId", because it's been reset.
12 // Only the "POST /login" request handler exists now.
13})

Be mindful when using .resetHandlers() with explicit next request handlers. It's important so that your tests remain deterministic and predictable.