You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cypress设置Local Storage异常:设置值与获取值不符求助

Cypress LocalStorage 设置异常问题解决

问题根源

你的代码存在两个核心问题:

  1. 错误的window对象:直接在beforeEach中调用window.localStorage.setItem时,这里的window是Cypress运行环境的全局对象,并非测试页面的浏览器window,所以设置的存储项根本不会同步到目标页面中。
  2. 执行顺序问题:visitPage('/')加载页面后,页面自身的初始化逻辑可能会将LocalStorage覆盖为默认的SE/SV值,即使你之前(错误地)设置了值,也会被页面的默认逻辑覆盖。

修正方案

方案一:页面加载后覆盖存储值

如果页面加载后才会设置默认值,可在页面加载完成后通过cy.window()获取浏览器window对象,再设置LocalStorage:

beforeEach(() => {
  cy.clearLocalStorage();
  cy.clearCookies();
  
  // 先加载页面
  visitPage('/');

  // 获取页面的window对象,操作其LocalStorage
  cy.window().then((win) => {
    win.localStorage.setItem('One', 'NL');
    win.localStorage.setItem('Two', 'NL');
    win.localStorage.setItem('Three', 'NL');
    
    // 验证设置结果
    const myItemOne = win.localStorage.getItem('One');
    const myItemTwo = win.localStorage.getItem('Two');
    const myItemThree = win.localStorage.getItem('Three');
    cy.log(myItemOne, myItemTwo, myItemThree);
  });
});

方案二:页面加载前注入存储值

如果页面在加载阶段就会读取LocalStorage并设置默认值,建议使用cy.visit的onBeforeLoad钩子,在页面加载前注入存储值:

beforeEach(() => {
  cy.clearLocalStorage();
  cy.clearCookies();
  
  // 在页面加载前设置LocalStorage
  cy.visit('/', {
    onBeforeLoad: (win) => {
      win.localStorage.setItem('One', 'NL');
      win.localStorage.setItem('Two', 'NL');
      win.localStorage.setItem('Three', 'NL');
    }
  });

  // 验证设置结果
  cy.window().then((win) => {
    const myItemOne = win.localStorage.getItem('One');
    const myItemTwo = win.localStorage.getItem('Two');
    const myItemThree = win.localStorage.getItem('Three');
    cy.log(myItemOne, myItemTwo, myItemThree);
  });
});

关键注意事项

  • 操作测试页面的浏览器存储时,必须通过cy.window()获取页面的window对象,不能直接使用Cypress环境的全局window。
  • 注意页面初始化逻辑的执行时机,根据实际情况选择在页面加载前或加载后设置存储值,避免被页面默认逻辑覆盖。

内容的提问来源于stack exchange,提问作者user21175044

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 01:25:19