- Introduction
- Getting started
- Philosophy
- Comparison
- Limitations
- Debugging runbook
- FAQ
- Basics
- Concepts
- Network behavior
- Integrations
- API
- CLI
- Best practices
- Recipes
- Cookies
- Query parameters
- Response patching
- Polling
- Streaming
- Network errors
- File uploads
- Responding with binary
- Custom worker script location
- Global response delay
- GraphQL query batching
- Higher-order resolver
- Keeping mocks in sync
- Merging Service Workers
- Mock GraphQL schema
- Using CDN
- Using custom "homepage" property
- Using local HTTPS
http
Intercept HTTP requests.
The http
namespace helps you create request handlers to intercept HTTP requests. This namespace is primarily useful for working with REST APIs since you can use its methods, like http.get()
and http.post()
, to describe resource operations.
Call signature
http.get<PathParams, RequestBodyType, ResponseBodyType>(
predicate: string | RegExp,
resolver: ResponseResolver<
HttpRequestResolverExtras<Params>,
RequestBodyType,
ResponseBodyType
>,
options?: RequestHandlerOptions
)
http.ts
Source code for the `http` namespace.
Standard methods
The http
namespace contains keys that represent WHATWG Fetch API HTTP methods. Use them to capture outgoing requests with the respective method.
http.get()
http.get('/user/:id', ({ params }) => {
const { id } = params
console.log('Fetching user with ID "%s"', id)
})
http.head()
http.head('/resource', () => {
return new Response(null, {
status: 200,
headers: {
'Content-Type': 'application/json',
'Content-Length': 1270,
'Last-Modified': 'Mon, 13 Jul 2020 15:00:00 GMT',
},
})
})
http.post()
http.post('/login', async ({ request }) => {
const info = await request.formData()
console.log('Logging in as "%s"', info.get('username'))
})
http.put()
http.put('/post/:id', async ({ request, params }) => {
const { id } = params
const nextPost = await request.json()
console.log('Updating post "%s" with:', id, nextPost)
})
http.patch()
http.patch('/cart/:cartId/order/:orderId', async ({ request, params }) => {
const { cartId, orderId } = params
const orderUpdates = await request.json()
console.log(
'Updating order "%s" in cart "%s":',
orderId,
cartId,
orderUpdates
)
})
http.delete()
http.delete('/user/:id', ({ params }) => {
const { id } = params
console.log('Deleting user with ID "%s"', id)
})
http.options()
http.options('https://api.example.com', () => {
return new Response(null, {
status: 200,
headers: {
Allow: 'GET,HEAD,POST',
},
})
})
Custom methods
The http
namespace also contains special keys that provide you with additional functionality but do not correspond to any HTTP methods:
http.all()
Creates a request handler that intercepts any request to a given endpoint regardless of its method.
import { http } from 'msw'
export const handlers = [
// This handler will capture ALL requests to the
// "/user" endpoint: GET, POST, DELETE, etc.
http.all('/user', () => {
// Handle the request.
}),
]
Using
http.all()
is also preferred when mocking custom HTTP methods.
Resolver argument
The response resolver function for every http.*
method has the following keys in its argument object:
Name | Type | Description |
---|---|---|
request | Request | Entire request reference. |
params | object | Request’s path parameters. |
cookies | object | Request’s cookies. |
You access these arguments on the response resolver argument object.
http.get('/user/:id', ({ request, params, cookies }) => {})
Handler options
All methods of the http
namespace accept an optional third argument representing request handler options. See below for the list of supported properties on that options object.
once
boolean
If set to true
, marks this request handler as used after the first successful match. Used request handlers have no effect on the outgoing traffic and will be ignored during request interception.
http.get('/greeting', () => HttpResponse.text('Hello world'), {
once: true,
})
Use the
.restoreHandlers()
method on theworker
/server
instance to mark all used request handlers as unused.
Related materials
Describing REST API
Learn about describing RESTful APIs.