【问题标题】:Jest testing mock functions return undefined (create react app project)开玩笑测试模拟函数返回未定义(创建反应应用项目)
【发布时间】:2021-05-02 13:55:50
【问题描述】:

我正在为一个带有 jest 的小型 react 应用程序做一个测试用例。
我已经在 describe 测试块的范围内声明了一个模拟函数。

当我在调试模式下运行测试时,我已经在接收模拟函数的反应组件内的断点处停止了模拟已声明但实现未定义。

有谁知道这种行为的原因是什么?

非常感谢!!!

 describe("Test App component", () => {
      describe("Test Component rendering", () => {
        const mockUtils = {
            debounceFunc: jest.fn((func) => {
              return func;
            }),
            isSomeStringEmpty: jest.fn(),
            confirmAction: jest.fn(),
          };
        test(`when render App component, then wrapper element should be rendered`, () => {
       
          render(<App utils={mockUtils} apiService={mockApiService} />);
    
          let appDiv = screen.getByTestId("app-test");
    
          expect(appDiv).toBeInTheDocument();
        });
    });

【问题讨论】:

    标签: javascript reactjs jestjs mocking create-react-app


    【解决方案1】:

    我找到了这种行为的答案。
    原因是我在这个项目中使用了 creat-react-app,默认情况下在 react-scripts node_modules/react-scripts/scripts/utils/createJestConfig.js 中使用。
    开玩笑的配置是用"resetMocks": true设置的

    这意味着在每次测试之前,jest 都会重置所有模拟。

    默认情况下,JEST 没有配置 "resetMocks": false 的 creat-react-app。

    要更改此配置,您只需在 package.json 的根级别添加此条目 "jest": { "resetMocks": false } .package.json example

    【讨论】:

      猜你喜欢
      • 2020-06-21
      • 1970-01-01
      • 1970-01-01
      • 2021-05-22
      • 2018-12-11
      • 2021-06-25
      • 2017-01-25
      • 2021-02-08
      • 2021-12-29
      相关资源
      最近更新 更多