Cookies

模拟响应 cookie。

使用直接 Fetch API Response 实例模拟响应 cookie 存在问题,因为 Set-Cookie 标头是无法设置的 禁用标头 标头之一。MSW 在其 HttpResponse 类中规避了这一限制,允许你在不损害响应完整性和安全性的情况下模拟响应 cookie。

¥Mocking response cookies using the direct Fetch API Response instance proves problematic because the Set-Cookie header is one of the forbidden headers that cannot be set. MSW circumvents this limitation in its HttpResponse class to allow you to mock response cookies without compromising your response’s integrity and security.

http.post('/login', () => {
  return new HttpResponse(null, {
    headers: {
      // Setting the "Set-Cookie" header on the mocked response
      // will set the cookies on the `document` as if they were
      // received from the server.
      'set-cookie': 'authToken=abc-123',
    },
  })
})

我们建议你使用第三方 Cookie 序列化库(例如 cookie)来处理模拟的 Cookie,设置其路径、到期日期、域名等。

¥We recommend you use third-party cookie serialization libraries, like cookie, to work with your mocked cookies, set their path, expiration date, domain, etc.