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

Local Storage模拟异常:同测试用例首测正常次测返回undefined

问题修复方案

先看你代码里的两个致命拼写/语法错误:

  • mockImpementaton拼写错误,正确写法是mockImplementation
  • JSON.stringify({id:'123' )}括号不匹配,应该改成JSON.stringify({id:'123'})

这两个错误导致localStorage的getItem mock没有正确初始化,第一个测试可能因为Jest的临时缓存侥幸运行,第二个测试就直接暴露了问题。

修正后的完整代码:

describe("Test",()=>{
  beforeEach(()=>{
    const localStorageMock={
      getItem: jest.fn().mockImplementation(()=>{
        return JSON.stringify({
          id:'123'
        });
      }),
      setItem: jest.fn()
    };
    Object.defineProperty(window,'localStorage',{value: localStorageMock});
  })
  
  test("First",()=>{
    console.log(localStorage.getItem());
    // 输出 '{"id":"123"}'
  })
  
  test("Second",()=>{
    console.log(localStorage.getItem());
    // 输出 '{"id":"123"}'
  })
})

额外提示:

  • 每次beforeEach重新创建mock对象并覆盖window.localStorage,保证每个测试用例都有独立干净的mock环境
  • Jest默认会隔离每个测试用例的执行上下文,修正错误后两个测试都能正常输出预期结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 13:48:19