LOGOMock Service Worker

use()

Prepends given request handlers to the current worker instance.

Request handler added after the initial setupWorker call is referred to as runtime request handler. When added, it affects network communication as any other request handler.

Examples

The .use() method of the worker instance can be called in any context where you have access to that worker instance.

Examples below will illustrate the usage of this method in E2E tests with Cypress. They assume you have the following mock definition file integrated in tests:

1// src/mocks.js
2import { setupWorker, rest } from 'msw'
3
4const worker = setupWorker(
5 rest.get('/book/:bookId', (req, res, ctx) => {
6 return res(ctx.json({ title: 'Lord of the Rings' }))
7 }),
8)
9
10// Make the `worker` and `rest` references available globally,
11// so they can be accessed in both runtime and test suites.
12window.msw = {
13 worker,
14 rest,
15}

Runtime request handler

1describe('Book detail', () => {
2 before(() => {
3 // Visit the book detail page that fetches
4 // a book information based on the book ID.
5 cy.visit('/book/abc-123')
6 })
7
8 test('handles user authentication', () => {
9 cy.window().then((window) => {
10 // Reference global instances set in "src/mocks.js".
11 const { worker, rest } = window.msw
12
13 worker.use(
14 rest.post('/book/:bookId/reviews', (req, res, ctx) => {
15 return res(ctx.json({ success: true }))
16 }),
17 )
18 })
19
20 // Requests to "POST /book/:bookId/reviews" will receive
21 // a mocked response according to the runtime request handler
22 // that is declared above.
23 })
24})

Permanent override

When a runtime request handler overlaps with an existing one (has the same predicate), the runtime handler always takes priority.

1describe('Login form', () => {
2 before(() => {
3 cy.visit('/login')
4 cy.window().then((window) => {
5 const { worker, rest } = window.msw
6
7 worker.use(
8 // Adds a "POST /login" runtime handler
9 // for all tests in this suite.
10 rest.post('/login', (req, res, ctx) => {
11 return res(ctx.json({ success: true }))
12 }),
13 )
14 })
15 })
16
17 test('handles user authentication', () => {
18 // Describe application interactions for this test.
19 })
20})

One-time override

If a response resolver function responds using res.once() method, it will affect only the first matching request. Any subsequent requests are passed to the next suitable request handler.

1describe('Book detail', () => {
2 before(() => {
3 cy.visit('/book/abc-123')
4 })
5
6 test('handles server error in the UI', () => {
7 cy.window().then((window) => {
8 const { worker, rest } = window.msw
9
10 worker.use(
11 rest.get('/book/:bookId', (req, res, ctx) => {
12 return res.once(
13 ctx.status(500),
14 ctx.json({ message: 'Internal server error' }),
15 )
16 }),
17 )
18 })
19
20 // Assuming our book page performs "GET /book/abc-123",
21 // it will get a mocked server error response on first load.
22 })
23})