http

拦截 HTTP 请求。

http 命名空间可帮助你创建请求处理程序来拦截 HTTP 请求。此命名空间主要用于使用 REST API,因为你可以使用其方法(如 http.get()http.post())来描述资源操作。

¥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

http 命名空间包含代表 WHATWG Fetch API HTTP 方法 的键。使用它们以相应的方法捕获传出请求。

¥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

http 命名空间还包含特殊键,这些键可为你提供附加功能,但不对应于任何 HTTP 方法:

¥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.
  }),
]

模拟自定义 HTTP 方法时,也首选使用 http.all()

¥Using http.all() is also preferred when mocking custom HTTP methods.

解析器参数

¥Resolver argument

每个 http.* 方法的响应解析器函数在其参数对象中都有以下键:

¥The response resolver function for every http.* method has the following keys in its argument object:

名称类型描述
requestRequest整个请求参考。
paramsobject请求的 路径参数
cookiesobject请求的 cookies

你可以在响应解析器参数对象上访问这些参数。

¥You access these arguments on the response resolver argument object.

http.get('/user/:id', ({ request, params, cookies }) => {})

处理程序选项

¥Handler options

http 命名空间的所有方法都接受一个可选的第三个参数,该参数表示请求处理程序选项。请参阅下面的选项对象支持的属性列表。

¥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

如果设置为 true,则在第一次成功匹配后将此请求处理程序标记为已使用。使用的请求处理程序对传出流量没有影响,并且在请求拦截期间将被忽略。

¥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,
})

worker/server 实例上使用 .restoreHandlers() 方法将所有使用的请求处理程序标记为未使用。

¥Use the .restoreHandlers() method on the worker/server instance to mark all used request handlers as unused.

相关材料

¥Related materials

Describing REST API

Learn about describing RESTful APIs.