resetHandlers()
Removes any request handlers that were added on runtime (after the initial setupWorker
call).
This function accepts an optional list of request handlers to override the initial handlers that allows 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.
1describe('Book detail', () => {2 before(() => {3 cy.visit('/book/abc-123')4 })56 afterEach(() => {7 return cy.window().then((window) => {8 const { worker } = window910 worker.resetHandlers()11 })12 })1314 test('allows to submit a book review', () => {15 cy.window().then((window) => {16 const { worker, rest } = window.msw1718 worker.use(19 rest.post('/book/:bookId/reviews', reviewResolver)20 )21 }2223 // Interact with the application to submit a new book review.24 })2526 test('renders book details', () => {27 // This test no longer handles "POST /book/:bookId/reviews",28 // because runtime request handlers have been reset in the29 // `afterEach` hook.30 })31})
Replacing initial handlers
When provided with a list of request handlers, .resetHandlers()
will additionally replace any initial request handlers with the explicitly provided ones.
1describe('Book detail', () => {2 before(() => {3 cy.visit('/book/abc-123')4 })56 test('renders book details', () => {7 // Render the page, triggering "GET /book/:bookId"8 })910 test('handles different scenario', () => {11 cy.window().then((window) => {12 const { worker, rest } = window.msw1314 worker.resetHandlers(15 rest.post('/login', (req, res, ctx) => {16 return res(ctx.json({}))17 }),18 )19 })2021 // This, and any subsequent test suites, know nothing22 // about "GET /book/:bookId" handler, because it has been23 // replaced by "POST /login".24 })25})
Be mindful when using
.resetHandlers()
with explicit next request handlers. It's important so that your tests remain deterministic and predictable.