LOGOMock Service Worker
  1. Api
  2. rest

rest

The rest namespace contains a set of Request handlers designed for convenient mocking of REST API requests.

Methods

Methods of this namespace represents REST API request methods:

  • rest.get()
  • rest.post()
  • rest.put()
  • rest.patch()
  • rest.delete()
  • rest.options()

Using a method under this namespace automatically creates a request handler that matches any requests with the respective REST API method. Additionally, such request handler accepts a request URL as the first parameter to narrow the match.

1import { rest } from 'msw'
2
3export const handlers = [
4 // Match a GET request to a third-party server.
5 rest.get('https://api.github.com/user/:login', (req, res, ctx) => {
6 return res(ctx.json({ login: req.params.login }))
7 })
8
9 // Match a POST request issued against the same origin
10 // as the current application.
11 rest.post('/author/:authorId/:postId', responseResolver),
12]

Custom methods

There are also custom methods that do not strictly represent REST API methods but provide a more convenient way to create request handlers.

  • rest.all()

Intercept any REST API request to a given path regardless of its method.

1import { rest } from 'msw'
2
3export const handlers = [
4 // Intercept all requests to the "/user" endpoint
5 // regardless of their method, and respond with a "403 Forbidden" response.
6 rest.all('/user', (req, res, ctx) => {
7 return res(ctx.status(403))
8 }),
9]

The path provided to rest.all() abides by the Request matching algorithm, meaning you can also use patterns and regular expressions.

Examples

1import { setupWorker, rest } from 'msw'
2
3const worker = setupWorker(
4 rest.get('/users/:userId', (req, res, ctx) => {
5 const { userId } = req.params
6
7 return res(
8 ctx.json({
9 id: userId,
10 firstName: 'John',
11 lastName: 'Maverick',
12 }),
13 )
14 }),
15)
16
17worker.start()