两个同名模块 - 模拟问题

dra*_*fly 5 reactjs jestjs

在 jest config 中setup.js,我模拟了两个模块:

jest.mock('somePath1/Translator');
jest.mock('somePath2/Translator');
Run Code Online (Sandbox Code Playgroud)

运行测试时我得到这个:

jest-haste-map: duplicate manual mock found:
  Module name: Translator
  Duplicate Mock path: C:\XXX\dev\YYY\src\components\ZZZ\services\__mocks__\Translator.js
This warning is caused by two manual mock files with the same file name.
Jest will use the mock file found in:
C:\XXX\dev\YYY\src\components\ZZZ\services\__mocks__\Translator.js
 Please delete one of the following two files:
 C:\XXX\dev\YYY\src\common\services\__mocks__\Translator.js
C:\XXX\dev\YYY\src\components\ZZZ\services\__mocks__\Translator.js
Run Code Online (Sandbox Code Playgroud)

然而,两者都是必需的,一些测试使用来自一个位置的服务,另一些则使用第二个位置的服务。

我该如何修复它?

小智 -1

您可以尝试使用 abeforeEach()jest.resetModules()从其中调用。然后只需模拟您对测试的依赖:

describe("some test", () => {
    beforeEach(() => {
       jest.resetModules();
    });

    test("Some test", () => {
        jest.mock("somePath1/Translator");
        // run tests here
    });

    test("Some other test", () => {
        jest.mock("somePath2/Translator");
        // run tests here
    });
});
Run Code Online (Sandbox Code Playgroud)

这将在每次测试之前清除您的模拟,因此您不应该与文件名发生任何冲突。