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

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 })
5
6 afterEach(() => {
7 return cy.window().then((window) => {
8 const { worker } = window
9
10 worker.resetHandlers()
11 })
12 })
13
14 test('allows to submit a book review', () => {
15 cy.window().then((window) => {
16 const { worker, rest } = window.msw
17
18 worker.use(
19 rest.post('/book/:bookId/reviews', reviewResolver)
20 )
21 }
22
23 // Interact with the application to submit a new book review.
24 })
25
26 test('renders book details', () => {
27 // This test no longer handles "POST /book/:bookId/reviews",
28 // because runtime request handlers have been reset in the
29 // `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 })
5
6 test('renders book details', () => {
7 // Render the page, triggering "GET /book/:bookId"
8 })
9
10 test('handles different scenario', () => {
11 cy.window().then((window) => {
12 const { worker, rest } = window.msw
13
14 worker.resetHandlers(
15 rest.post('/login', (req, res, ctx) => {
16 return res(ctx.json({}))
17 }),
18 )
19 })
20
21 // This, and any subsequent test suites, know nothing
22 // about "GET /book/:bookId" handler, because it has been
23 // 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.