node.js - 如何在 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)
我希望能够与注入的模拟进行交互,看看它是否在单元测试中被调用。
解决方案
假设你想监视 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)
推荐阅读
- python - 我可以使用哪些技术使我的合并排序实现运行得更快?
- json - 将 JSON 导入 Excel 时出现数据格式错误
- python-3.x - 当我增加 Bitvector 的长度时,z3py solver.check() 从“sat”变为“unknown”
- angular - 从 ngFor 中动态创建的多个 mat-slider 获取值
- python - 尝试使用 Python 进行顶级包之外的相对导入
- r - 使用 grepl R 子集列表
- angular - Observable 而不是函数 angular 8 9
- groovy - 如何在 groovy 脚本中返回类成员字符串
- html - 如何通过单击检查 Angular 中的材质复选框?
- mapbox - 如何在 MAPBOX 中调整窗口大小时同时适应边界并设置最大边界?