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'34const server = setupServer(5 rest.get('/book/:bookId', (req, res, ctx) => {6 return res(ctx.json({ title: 'Lord of the Rings' }))7 }),8)910beforeAll(() => {11 server.listen()12})1314afterEach(() => {15 server.resetHandlers()16})1718afterAll(() => {19 server.close()20})2122test('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 )2728 // Performing a "POST /book/:bookId/reviews" request29 // will get the mocked response from `bookReviewResolver`.30})3132test('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))23test('first test', () => {4 // Can handle "GET /book/:bookId".5})67test('second test', () => {8 server.resetHandlers(rest.post('/login', loginResolver))910 // This, and any subsequent tests, will NOT handle11 // "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.