处理请求和响应 cookie。

¥Read request cookies

你可以使用响应解析器的 cookies 参数访问拦截的请求 cookie:

¥You can access the intercepted request cookies using the cookies argument of the response resolver:

import { http, HttpResponse } from 'msw'
export const handlers = [
  http.get('/api/user', ({ cookies }) => {
    if (!cookies.authToken) {
      return new HttpResponse(null, { status: 403 })
    return HttpResponse.json({ name: 'John' })

请注意,cookies 的值尊重 请求凭据,并且可能包含比请求中最初发送的更多数据(例如,当请求的 credentials 属性设置为 "include" 时)。

¥Note that the value of cookies respects Request credentials, and may contain more data than originally sent in the request (e.g. when the credentials property of the request was set to "include").

¥Mock response cookies

模拟响应 cookie 通常具有挑战性,因为出于安全原因,Fetch 规范 forbids 在手动构建的响应上设置 Set-CookieSet-Cookie2 标头。

¥Mocking response cookies is often challenging because the Fetch specification forbids setting Set-Cookie and Set-Cookie2 headers on manually constructed responses for security reasons.

由于 Mock Service Worker 在客户端上执行,因此它可以通过直接在 document.cookie 上设置模拟响应 cookie 来解决此限制,就好像它们是从服务器接收的一样。这种方法不会损害响应安全性,同时仍允许你测试应用的 cookie 处理逻辑。

¥Since Mock Service Worker executes on the client, it can work around this limitation by setting mocked response cookies directly on the document.cookie, as if they were received from the server. This approach doesn’t compromise response security while still allowing you to test your application’s cookie handling logic.

import { http, HttpResponse } from 'msw'
export const handlers = ['/login', () => {
    return new HttpResponse(null, {
      headers: {
        // Setting the "Set-Cookie" mocked response header
        // will forward these cookies onto "document" as if they
        // were sent from the server.
        'Set-Cookie': 'authToken=abc-123',

请注意,你必须使用 HttpResponse 类才能设置模拟响应 cookie。这样,MSW 可以检测响应 cookie,因为一旦设置,就无法在 JavaScript 中访问它们。

¥Note that you must use the HttpResponse class in order to set mocked response cookies. This way MSW can detect response cookies because they cannot be accessed in JavaScript once set.