You need to enable JavaScript to run this app. 如何在Selenium JS中交互操作Local Storage?脚本执行返回null问题求解
优惠活动
大模型
产品
解决方案
定价
更多

如何在Selenium JS中交互操作Local Storage?脚本执行返回null问题求解

自动化测试场景需求

使用JavaScript、Selenium、Cucumber搭建的自动化测试流程中,需要操作Local Storage内的指定存储值,完成删除、修改操作,以此模拟token过期的前置测试条件,目前未找到可正常运行的Local Storage交互实现路径。

已尝试的实现方案与异常情况

  • 第一版实现:通过executeScript接口传入模板字符串形式的JS脚本,依次执行Local Storage读取、指定键值删除的逻辑
    具体代码:
    Given('(the user )has an expired token', async function() {
     console.log(await this.driver.executeScript(`
     window.localStorage.getItem('key')`));
    
     await this.driver.executeScript(`
     window.localStorage.removeItem('key')`);
    });
    
    执行表现:测试流程运行后,控制台打印的脚本返回值为null;逐行核对逻辑后确认,相同代码手动在浏览器控制台执行可正常获取预期结果,仅在自动化测试流程中出现返回值异常。
  • 第二版实现:参考社区反馈调整调用方式,在executeScript接口中传入原生函数形式的取值逻辑
    具体代码:
    Given('(the user )has an expired token', async function() {
     console.log(await this.driver.executeScript(function () {
      localStorage.getItem("key");
      }))
    });
    
    执行表现:调整后依然无法正常运行,未实现对Local Storage指定值的预期操作。

核心诉求

需要适配当前技术栈、可直接落地运行的Selenium JS与Local Storage交互参考示例,支撑测试流程中对Local Storage存储值的读取、删除、修改操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.27 07:36:06