首页 > 解决方案 > 如何在 ES6 类中使用 JestJS 注入依赖进行模拟?

问题描述

我正在尝试在一个小型 NodeJS 项目中进行一些依赖反转。我想要模拟可以注入其他类的个人类的实例。

这是最新的节点和笑话版本,我已经阅读了 Jest 文档,似乎没有什么是我想要的。

class A {

    getStr(): string {
        return "bob";
    }
}

class B {
    private a: A;

    constructor(a: A){
        this.a = a;
    }

    getA(): string {
        return a.getStr();
    }
}

const b = new B(mocked instance of A)

我希望能够与注入的模拟进行交互,看看它是否在单元测试中被调用。

标签: node.jsmockingjestjs

解决方案


假设你想监视 A 的函数,你可以这样做(如果你想继续使用类符号):

class MockA {
    constructor() {
       this.getStr = jest.fn()
    }
}

const mockedA = new MockA()
const b = new B(mockedA)

然后为了测试它是否被调用,你可以这样做:

b.getA();
expect(a.getStr.mock.calls.length).toBe(1)

要创建没有类的模拟,您可以执行以下操作:

const mockedGetStr = jest.fn()
const b = new B({ getStr: mockedGetStr })
b.getA();
expect(a.getStr.mock.calls.length).toBe(1)

推荐阅读