Cypress无法从Local Storage获取认证令牌问题求助
解决Cypress中localStorage.getItem返回null的问题
问题代码
const token = window.localStorage.getItem("token"); cy.request({ method: "POST", url: "xxxxxxxxxxxxxxx", headers: { Authorization: token, }, body: { }, })
打印token结果为null,但浏览器Local Storage中已存在键为"token"的正确令牌,且无嵌套结构。
核心原因
Cypress测试代码运行在Node.js环境,直接访问window.localStorage时,实际访问的是Node环境中的window对象(并非浏览器的window),因此无法获取到浏览器Local Storage里的内容,返回null。
解决方案
通过cy.window()进入浏览器上下文,再获取Local Storage中的token:
cy.window().then((win) => { const token = win.localStorage.getItem("token"); cy.request({ method: "POST", url: "xxxxxxxxxxxxxxx", headers: { Authorization: token, }, body: { }, }); });
验证步骤(可选)
如果想确认token是否正确获取,可以在回调中打印验证:
cy.window().then((win) => { const token = win.localStorage.getItem("token"); console.log("获取到的token:", token); // 在浏览器控制台查看输出 });
内容的提问来源于stack exchange,提问作者Nils Schumann
相关产品推荐
相关产品推荐

