Mock 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

Each method in this namespace represents a REST API request method:

  • 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 { setupWorker, rest } from 'msw'
2
3setupWorker(
4 // Match all "POST" requests to the given path
5 rest.post('/author/:authorId/:postId', responseResolver),
6)

Here are some examples of request URLs that would match the request handler above:

  • POST /author/1/2
  • POST /author/123-abc/456-def

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()