我正在开玩笑地设置 e2e 测试,我希望在我调用它时让 fetch 发送我的 cookie:
const userinfo = await fetch('/api/auth/me')
我已经设置了我的笑话配置
testEnvironmentOptions: {
url: 'http://localhost:5544/'
},
并将
import 'whatwg-fetch'
添加到我的 jest.setup.js 文件中,这很棒,它让我达到了我的获取请求在相对路径上工作的程度。然而,我一生都无法获取 fetch 来发送我的身份验证 cookie。
我已将 cookie 添加到文档中,如下所示
Object.defineProperty(window.document, 'cookie', {
writable: true,
value: 'auth=...',
});
我尝试将 fetch
credentials
属性设置为 include
和 same-origin
但没有成功。我通读了 CORS 指南,但这都是关于如何让浏览器设置 cookie - 就我而言,我已经自己设置了 cookie。在我的服务器上,请求总是在不附加 cookie 的情况下通过。我很困惑,以前有其他人解决过这个问题吗?
更新: 我尝试了更多但没有成功:
Object.defineProperty(window.document, 'cookie', {
writable: true,
value: 'auth=...;domain=localhost:5544;path=/',
});
const userinfo = await fetch('/api/auth/me', {credentials: "same-origin", mode: 'same-origin'});
{
referer: 'http://localhost:5544/',
'user-agent': 'Mozilla/5.0 (darwin) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/20.0.3',
'accept-language': 'en',
accept: '*/*',
'accept-encoding': 'gzip, deflate',
host: 'localhost:5544',
connection: 'keep-alive'
}
这些事情都没有帮助,请求仍然在不附加 cookie 的情况下完成
明白了!我花了一段时间才弄清楚发生了什么,但基本上 jsdom 有自己的
cookie
implementation,因此调用 Object.defineProperty
会覆盖 jsdom 中的实现。惊人的。您所要做的就是设置
document.cookie = 'auth=...'
你就可以开始了。我还发现 fetch 默认为
{credentials: 'same-origin'}
所以我的调用可以是:
await fetch(`/api/auth/me`)
一切都是金子。