Local Storage模拟异常:同测试用例首测正常次测返回undefined
问题修复方案
先看你代码里的两个致命拼写/语法错误:
mockImpementaton拼写错误,正确写法是mockImplementationJSON.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
相关产品推荐
相关产品推荐

