Jest中Fetch polyfill无法携带Cookie的问题排查
方案1:手动在Fetch请求头中添加Cookie
这是测试环境下最直接的解决方式,无需依赖DOM的Cookie机制,直接构造请求头:
const userinfo = await fetch('/api/auth/me', { headers: { 'Cookie': 'auth=your-auth-token; path=/' } });
方案2:使用jsdom的CookieJar API设置Cookie
jsdom的document.cookie实际依赖内部的CookieJar存储,直接用Object.defineProperty修改表面值不会同步到CookieJar中,需要通过官方API写入:
// 在测试用例或jest.setup.js中执行 await window.document.cookieJar.setCookie( 'auth=your-auth-token; path=/', 'http://localhost:5544/', (err) => { if (err) throw err; } ); // 之后正常调用fetch,credentials设为same-origin或include即可 const userinfo = await fetch('/api/auth/me', { credentials: 'same-origin' });
方案3:全局Mock Fetch自动携带Cookie
如果所有测试用例都需要携带相同Cookie,可以全局Mock fetch实现:
// 在jest.setup.js中配置 const originalFetch = window.fetch; window.fetch = async (url, options = {}) => { options.headers = new Headers(options.headers); options.headers.append('Cookie', 'auth=your-auth-token; path=/'); return originalFetch(url, options); };
为什么之前的方法无效?
你用Object.defineProperty直接修改document.cookie的value,只是覆盖了属性的返回值,并没有将Cookie真正存入jsdom的CookieJar中。而whatwg-fetch在jsdom环境下发起请求时,会从CookieJar读取Cookie,而非直接读取document.cookie的表面值,因此服务器接收不到你设置的Cookie。
内容的提问来源于stack exchange,提问作者Tim
相关产品推荐
相关产品推荐

