Jest测试中如何正确mock localforage.getItem()方法
报错原因
mock不生效由三个写法问题导致:
jest.mock必须放在测试文件顶层作用域,不能写在test用例块内部。Jest执行测试前会自动把所有jest.mock调用提升到文件最顶部,写在用例内部的mock无法被正确提升,不能拦截模块导入。- localforage 以ESModule默认导出的形式暴露实例对象,当前mock只写了具名导出的
getItem,没有提供默认导出,业务代码中导入的localforage值为undefined,读取getItem时就会抛出类型错误。 - localforage 的所有API都是异步Promise风格,当前mock的
getItem直接返回普通对象,即使mock加载成功,后续调用.then()时也会触发报错,需要返回Promise包裹的模拟值。
修复方案
将测试文件调整为如下写法即可:
// jest.mock 必须放在test块外部的顶层作用域 jest.mock('localforage', () => ({ __esModule: true, // 补充默认导出,匹配业务代码 import localforage from 'localforage' 的导入写法 default: { getItem: jest.fn((key: string) => Promise.resolve({ name: 'John' })) } })); test('render App component', () => { render(<App />); // 可选:增加调用断言验证逻辑 // expect(localforage.getItem).toHaveBeenCalledWith('20220622'); });
如果不想手写完整mock,也可以用Jest自动mock能力:在文件顶层写jest.mock('localforage'),再在测试用例内通过localforage.getItem.mockResolvedValue({ name: 'John' })定义返回值即可。
内容的提问来源于stack exchange,提问作者Kenta Konno
相关产品推荐
相关产品推荐

