【问题标题】:Extract jest.mock to seperate util function提取 jest.mock 以分离 util 函数
【发布时间】:2023-02-11 19:04:54
【问题描述】:

我想制作一个通用的jest.mock 函数以在多个测试文件中使用。 当我直接在测试文件中使用 jest.mock 时,第一个示例有效。但是第二个例子没有

// EXAMPLE 1
// this works
jest.mock("third-paty-module", () => {
  return {
    MyComponent: props => {
      return <input {...props} />;
    }
  };
});
test("my test", () => {
  // then assert
});

// EXAMPLE 2
// this doesn't work

// test.config.js
export function mockCustom() {
  jest.mock("third-paty-module-which-uses-webcomponents", () => {
    return {
      MyComponent: props => {
        return <input {...props} />;
      }
    };
  });
}

// file.test.js
import { mockCustom } from "../../config/test.config.js";

mockCustom();

test("my test", () => {
  // then assert
});

使用 jest.doMock 时我没有收到任何错误,但这根本不会模拟我的组件。

【问题讨论】:

  • jest.mock得到吊起在任何其他导入之上,您的mockCustom 没有。
  • 有什么办法吗?
  • 如果您想分解出模拟的实际实现,请参阅jestjs.io/docs/manual-mocks
  • 这没有用,如果我将它解压到 __mocks__ 目录也没有区别

标签: javascript reactjs unit-testing jestjs


【解决方案1】:

在 Jest 中,您可以使用以下方法将 jest.mock 函数提取到实用程序文件jest.genMockFromModule功能。您可以这样做:

例如,创建一个要存储模拟函数的实用程序文件嘲笑/moduleName.js. In the utility file, add the following code:

export default jest.genMockFromModule('moduleName');

在您的测试文件中,像这样导入模拟函数:

import moduleNameMock from './__mocks__/moduleName';

jest.mock('./moduleName', () => moduleNameMock);

像往常一样在测试用例中使用模拟函数。 通过使用 jest.genMockFromModule,您可以生成一个与原始模块具有相同接口的模拟函数。这样,您可以在多个测试文件中重用模拟,并为所有测试保持相同的行为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多