unit-testing - 使用 jestjs 进行单元测试隔离

标签 unit-testing ecmascript-6 jestjs

用 jest 处理测试隔离的最佳方法是什么?我想用静态方法测试一个 ES6 类并模拟单元测试不直接涉及的方法。

我的类(class)文件:

class Util {

    static getFirstName() {
        return "John";
    }

    static getLastName() {
        return "Doe";
    }

    static getFullName(){
        return `${Util.getFirstName()} ${Util.getLastName()}`;
    }
}

我的测试文件:
import Util from '../src/util';

test("Test getFullName", () => {
    Util.getFirstName = jest.fn().mockReturnValue("MockFirstName");
    Util.getLastName = jest.fn().mockReturnValue("MockLastName");

    expect(Util.getFullName()).toBe("MockFirstName MockLastName")
});

test("Test getFirstName", () => {
    expect(Util.getFirstName()).toBe("John")
});

test("Test getLastName", () => {
    expect(Util.getLastName()).toBe("Doe")
});

这样,我的最后两个测试将失败,因为在第一个测试中设置的模拟仍然处于事件状态。

最佳答案

假设那些 import语句正在转换为 require ,您应该可以使用 resetModules :

beforeEach(() => {
    // Clears the require cache so that a new module is require'd
    // before each test.
    jest.resetModules();
});

然后在每个测试中,您需要 require 模块:
test("name", () => {
    const { default: Util } = require("../src/util");
});

或者,如果您可以使用动态导入语法:
test("name", () => import("../src/util")
    .then(({ default: Util }) => {
        expect(Util.getFirstName()).toBe("John");
    })
);

关于unit-testing - 使用 jestjs 进行单元测试隔离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43275143/

相关文章:

javascript - 在关于 expect.throw 的链中进行单元测试时遇到问题

python 模拟第三方模块

javascript - 必须传递一个空对象作为参数 ES6

reactjs - enzyme 和 Jest : How to simulate/test material-ui dropzone onChange handler when dropzone component is third party module?

unit-testing - 是否可以在同一个单元测试中模拟 Controller 并访问 FormTagLib?

python - 我什么时候应该创建多个测试函数,我应该为全局变量使用 pytest fixtures?

javascript - react 字符串常量

javascript - ES5 和 ES6 中的 Angular 2 依赖注入(inject)

jestjs - 如何测试验证管道在 NestJS 上抛出形状不正确的请求的预期错误

reactjs - Jest 测试仅在覆盖范围内失败