mswMock Service Worker
  1. Api
  2. request

request

Request (req) is an object that stores the information about a matched request.

Unlike a NodeJS Request, the request object in Mock Service Worker is a partial request representation. This is due to the limitations on the nature of the data that can be transferred between a Service Worker and a client processes.

The req object of the same response resolve will be different in browser and Node environment. Certain request properties are not available in Node (i.e. credentials, integrity or destination). The values of such properties are set to sensible defaults when referenced in Node environment.

Properties

PropertyType
urlURL
bodystring, Record<string, any>
methodRequest.method
headersRequest.headers
cookiesRecord<string, string>
paramsRecord<string, string>
bodyUsedRequest.bodyUsed
cacheRequest.cache
modeRequest.mode
credentialsRequest.credentials
redirectRequest.redirect
referrerRequest.referrer
referrerPolicyRequest.referrerPolicy
integrityRequest.integrity
destinationRequest.destination
keepaliveboolean

GraphQL

When mocking a GraphQL API, the req object contains the following extra properties:

PropertyType
variablesRecord<string, string>

Examples

Path parameter

1rest.post('/user/:userId/articles', (req, res, ctx) => {
2 const { userId } = req.params
3 return res(ctx.text(userId))
4})

GraphQL variable

1graphql.mutation('Login', (req, res, ctx) => {
2 const { username } = req.variables
3
4 return res(
5 ctx.data({
6 user: { name: 'John ' },
7 }),
8 )
9})