如何使用 Jest 测试忽略 import 语句?

Gol*_*lsh 7 javascript unit-testing typescript jestjs

我正在尝试为工厂模块编写测试。该工厂模块导入一个对象模块,然后返回给定特定字符串的新实例。它导入的对象导入更多的东西,并且它正在导入的对象之一导入另一个对象,该对象导入另一个依赖于某些环境变量的脚本。该脚本运行后无法找到所需的环境变量,甚至在测试开始之前就终止了该进程。

\n

我认为没有必要导入这么多层来测试这个特定的工厂。解决这个问题的正确方法是什么?请注意,我对 javascript/typescript 非常陌生,因此任何对包导入的工作方式的了解都会有所帮助。

\n

jest.mock 不会阻止底层对象上的 import 语句运行。

\n
//object-factory.ts\nimport {AnObject} from \'../interfaces/an-object\';\nimport VeryNiceObject from \'./very-nice-object\';\n\nexport const VERY_NICE_STRING = \'this-string-is-very-nice\'\n\nexport class ObjectFactory {\n    private readonly str: string;\n\n    constructor(str: string) {\n        this.str = str;\n    }\n\n    public build(): AnObject {\n        switch (this.str) {\n            case VERY_NICE_STRING:\n                return new VeryNiceObject();\n            default:\n                throw new Error(`Unknown string ${this.str}`);\n        }\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

我正在尝试隔离这个正在测试的模块。我的测试看起来像这样 -

\n
jest.mock("../very-nice-object")\n\nimport {AnObject} from "../../interfaces/an-object";\nimport {ObjectFactory, VERY_NICE_STRING} from "../object-factory"; //FAILS HERE\nimport VeryNiceObject from "../very-nice-object";\n\ndescribe(\'object-factory\', () => {\n    test("build returns VeryNiceObject", () => {\n        const factory = new ObjectFactory(VERY_NICE_STRING)\n        const objectResult = factory.build()\n        expect(objectResult instanceof VeryNiceObject)\n    })\n});\n\n
Run Code Online (Sandbox Code Playgroud)\n

我还尝试在文件顶部使用 automock 运行,但由于不同的原因而失败。

\n
jest.autoMockOn() \n...rest of test\n
Run Code Online (Sandbox Code Playgroud)\n
  \xe2\x97\x8f Test suite failed to run\n\n    TypeError: Expected a string\n\n      at escapeStringRegexp (node_modules/colors/lib/colors.js:80:11)\n      at node_modules/colors/lib/colors.js:101:18\n          at Array.forEach (<anonymous>)\n      at node_modules/colors/lib/colors.js:99:27\n      at Object.<anonymous> (node_modules/colors/lib/colors.js:109:3)\n
Run Code Online (Sandbox Code Playgroud)\n

ser*_*inc 12

只是为了节省您的点击次数:在/sf/answers/2856677771/中,@Andrew (go upvote) 建议使用:

 jest.mock("../../src/styles.less", () => jest.fn());
Run Code Online (Sandbox Code Playgroud)

如果没有工厂,jest 会尝试解析文件以找出要模拟的名称。

  • 读者可能知道这也适用于包: `jest.mock('my-npm-package', () =&gt; jest.fn())` (5认同)