【发布时间】:2020-08-08 02:42:06
【问题描述】:
我正在尝试为工厂模块编写测试。该工厂模块导入一个对象模块,然后返回给定特定字符串的新实例。 它导入的对象导入了更多的东西,它正在导入的一个东西导入另一个东西,它导入另一个依赖于某些环境变量的脚本。该脚本运行,找不到它需要的环境变量,甚至在测试开始之前就终止了进程。
我认为没有必要导入这么多层来测试这个特定的工厂。解决这个问题的正确方法是什么?请注意,我对 javascript/typescript 非常陌生,因此对包导入应该如何工作的任何见解都会有所帮助。
jest.mock 不会阻止底层对象上的 import 语句运行。
//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 ConsumerGroupFactory(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)
【问题讨论】:
标签: javascript typescript unit-testing jestjs