LOGOMock Service Worker

Mocking REST API

Imports

In our src/mocks/handlers.js file let's import the essentials we need for mocking a REST API. They are grouped under the rest namespace exposed by the library.

Import rest from the msw package:

1// src/mocks/handlers.js
2import { rest } from 'msw'

Request handler

To handle a REST API request we need to specify its method, path, and a function that would return the mocked response.

In this tutorial we will be mocking a basic login flow for our user. This flow implies handling two requests:

  • POST /login, to allow our user to log in;
  • GET /user, to return the information about the logged in user.

Create request handlers by calling rest[METHOD] and providing a request path:

1// src/mocks/handlers.js
2import { rest } from 'msw'
3
4export const handlers = [
5 // Handles a POST /login request
6 rest.post('/login', null),
7
8 // Handles a GET /user request
9 rest.get('/user', null),
10]

Response resolver

To respond to an intercepted request we have to specify a mocked response using a response resolver function.

Response resolver is a function that accepts the following arguments:

  • req, an information about a matching request;
  • res, a functional utility to create the mocked response;
  • ctx, a group of functions that help to set a status code, headers, body, etc. of the mocked response.

Provide response resolvers to the previously defined request handlers:

1// src/mocks/handlers.js
2import { rest } from 'msw'
3
4export const handlers = [
5 rest.post('/login', (req, res, ctx) => {
6 // Persist user's authentication in the session
7 sessionStorage.setItem('is-authenticated', 'true')
8
9 return res(
10 // Respond with a 200 status code
11 ctx.status(200),
12 )
13 }),
14
15 rest.get('/user', (req, res, ctx) => {
16 // Check if the user is authenticated in this session
17 const isAuthenticated = sessionStorage.getItem('is-authenticated')
18
19 if (!isAuthenticated) {
20 // If not authenticated, respond with a 403 error
21 return res(
22 ctx.status(403),
23 ctx.json({
24 errorMessage: 'Not authorized',
25 }),
26 )
27 }
28
29 // If authenticated, return a mocked user details
30 return res(
31 ctx.status(200),
32 ctx.json({
33 username: 'admin',
34 }),
35 )
36 }),
37]

Utilize things like sessionStorage, localStorage, or IndexedDB to handle more complex API scenarios and user interactions.

Next step

The request handlers are complete, yet there is one last step to perform: integrate the mocking.

Integrate/docs/getting-started/integrate