Mocking HTTP
Learn about intercepting HTTP requests.
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.
import { http, HttpResponse } from 'msw/http'
http.get('/user/:id', ({ request, params }) => {
return HttpResponse.json({ id: params.id })
})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 }) => {
console.log('Fetching user with ID "%s"', params.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',
},
})
})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/http'
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.
The response resolver function for every http.* method has the following keys in its argument object:
| Name | Type | Description |
|---|---|---|
request | Request | Entire request reference. |
requestId | string | Unique ID of the intercepted request. |
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 }) => {})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 booleanIf 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/serverinstance to mark all used request handlers as unused.
Mocking HTTP
Learn about intercepting HTTP requests.