javascript - 如何使用 Jest 测试忽略导入语句?

标签 javascript typescript unit-testing jestjs

我正在尝试为工厂模块编写测试。该工厂模块导入一个对象模块,然后返回给定特定字符串的新实例。 它导入的对象导入了更多的东西,它正在导入的一个东西导入另一个东西,它导入另一个依赖于某些环境变量的脚本。该脚本运行,找不到它需要的环境变量,甚至在测试开始之前就终止了进程。
我认为没有必要导入这么多层来测试这个特定的工厂。解决这个问题的正确方法是什么?请注意,我对 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/

相关文章:

javascript - 遍历枚举,将枚举元素指定为参数

angular - TypeScript [警告] 转换为 CommonJS,考虑设置模块 : "system" in typescript Options

unit-testing - 导出 Golang 包进行测试?

unit-testing - 如何对以事件区域作为输入的函数进行单元测试?

javascript - 从电子邮件的字符串正文中删除格式标签

css - 如何在 Angular2 中的路由器 socket 旁边放置垂直按钮

javascript - MinMax 算法未按预期工作

使用 ant 和库项目 R18 的 Android 单元测试

javascript - 引用错误: request is not defined in NodeJS Session

javascript - 拼接方法问题