我正在尝试为工厂模块编写测试。该工厂模块导入一个对象模块,然后返回给定特定字符串的新实例。 它导入的对象导入了更多的东西,它正在导入的一个东西导入另一个东西,它导入另一个依赖于某些环境变量的脚本。该脚本运行,找不到它需要的环境变量,甚至在测试开始之前就终止了进程。
我认为没有必要导入这么多层来测试这个特定的工厂。解决这个问题的正确方法是什么?请注意,我对 javascript/typescript 非常陌生,因此对包导入应该如何工作的任何见解都会有所帮助。
jest.mock 不会阻止底层对象上的导入语句运行。
//object-factory.ts
import {AnObject} from '../interfaces/an-object';
import VeryNiceObject from './very-nice-object';
export const VERY_NICE_STRING = 'this-string-is-very-nice'
export class ObjectFactory {
private readonly str: string;
constructor(str: string) {
this.str = str;
}
public build(): AnObject {
switch (this.str) {
case VERY_NICE_STRING:
return new VeryNiceObject();
default:
throw new Error(`Unknown string ${this.str}`);
}
}
}
我正在尝试隔离这个被测模块。我的测试看起来像这样 -jest.mock("../very-nice-object")
import {AnObject} from "../../interfaces/an-object";
import {ObjectFactory, VERY_NICE_STRING} from "../object-factory"; //FAILS HERE
import VeryNiceObject from "../very-nice-object";
describe('object-factory', () => {
test("build returns VeryNiceObject", () => {
const factory = new ObjectFactory(VERY_NICE_STRING)
const objectResult = factory.build()
expect(objectResult instanceof VeryNiceObject)
})
});
我还尝试在文件顶部使用 automock 运行,但由于不同的原因而失败。jest.autoMockOn()
...rest of test
● Test suite failed to run
TypeError: Expected a string
at escapeStringRegexp (node_modules/colors/lib/colors.js:80:11)
at node_modules/colors/lib/colors.js:101:18
at Array.forEach (<anonymous>)
at node_modules/colors/lib/colors.js:99:27
at Object.<anonymous> (node_modules/colors/lib/colors.js:109:3)
最佳答案
只是为了节省您的点击:在https://stackoverflow.com/a/40809682/1587329 , @Andrew (go upvote) 建议使用:
jest.mock("../../src/styles.less", () => jest.fn());
如果没有工厂,jest 会尝试解析文件以找出要模拟的名称。
关于javascript - 如何使用 Jest 测试忽略导入语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61409827/