首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用Jest模拟localforage.getItem()?

如何用Jest模拟localforage.getItem()?
EN

Stack Overflow用户
提问于 2022-06-22 09:18:05
回答 1查看 182关注 0票数 1

我正在使用本地饲料为代码编写一个测试,并一次又一次地获得undefined (reading 'getItem')

  • App.test.tsx
代码语言:javascript
复制
test('render App component', () => {
  jest.mock('localforage', () => ({
    getItem: (item: string) => {
      return { name: 'John' };
    },
  }));

  render(<App />);
});

但徒然..。

代码语言:javascript
复制
  ● render App component

    TypeError: Cannot read properties of undefined (reading 'getItem')

      124 |
      125 |   useEffect(() => {
    > 126 |     localforage.getItem('20220622').then((values) => console.table(values));
          |                 ^
      127 |   }, []);
      128 |
  • App.tsx
代码语言:javascript
复制
const App = () => {
  useEffect(() => {
    localforage.getItem('20220622').then((values) => console.table(values));
  }, []);

  return (<p>Hello.</p>);
}
EN

回答 1

Stack Overflow用户

发布于 2022-10-05 16:19:09

您可以通过在根localforage.ts文件夹中创建一个__mocks__文件来模拟这个问题。在这里,您可以模拟这个模块中的任何值或函数,Jest将自动使用该函数。

代码语言:javascript
复制
// <rootDir>/__mocks__/localforage.ts

const mock = {
  setItem: async () => undefined,
  getItem: async () => undefined,
  removeItem: async () => undefined,
};

export default mock;

文档

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72712818

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档