javascript - 未找到 sinon 存根类
问题描述
我开始使用 sinon 编写单元测试用例并面临以下问题。
我的文件.js
module.exports = class A{
constructor(classB_Obj){
this.classBobj = classB_Obj;
classBobj.someFunctionOfClassB(); // error coming here
}
doSomething(){
}
}
B类在哪里
myfile2.js
module.exports = class B{
constructor(arg1, arg2){
this.arg1 = arg1;
this.arg2 = arg2;
}
someFunctionOfClassB(){
}
}
当我测试 A 类并使用 sinon 存根 B 类时
const myfile2 = require('../myfile2').prototype;
const loggerStub = sinon.stub(myfile2, 'someFunctionOfClassB');
在执行它时给出异常
classBobj.someFunctionOfClassB 不是函数。
存根的正确方法是什么?我不想实例化 B 类。
解决方案
这是单元测试解决方案:
myfile.js
:
module.exports = class A {
constructor(classB_Obj) {
this.classBobj = classB_Obj;
this.classBobj.someFunctionOfClassB();
}
doSomething() {}
};
myfile2.js
:
module.exports = class B {
constructor(arg1, arg2) {
this.arg1 = arg1;
this.arg2 = arg2;
}
someFunctionOfClassB() {}
};
myfile.test.js
:
const A = require("./myfile");
const B = require("./myfile2");
const sinon = require("sinon");
describe("52559903", () => {
afterEach(() => {
sinon.restore();
});
it("should pass", () => {
const bStub = sinon.createStubInstance(B, {
someFunctionOfClassB: sinon.stub(),
});
new A(bStub);
sinon.assert.calledOnce(bStub.someFunctionOfClassB);
});
});
带有覆盖率报告的单元测试结果:
myfile
✓ should pass
1 passing (10ms)
----------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------------|----------|----------|----------|----------|-------------------|
All files | 87.5 | 100 | 57.14 | 87.5 | |
myfile.js | 100 | 100 | 50 | 100 | |
myfile.test.js | 100 | 100 | 100 | 100 | |
myfile2.js | 33.33 | 100 | 0 | 33.33 | 3,4 |
----------------|----------|----------|----------|----------|-------------------|
源代码:https ://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/52559903
推荐阅读
- c++ - 为什么这个程序占用太多内存?
- api - 如何在 Flutter 中使用 Future 和 Uri.Https 构造函数进行 API 调用
- android - 硬件键在 Flutter 上显示屏幕键盘
- git - 如何重命名在其子目录中有子模块的 git 文件夹
- javascript - 使用 Webpack 动态导入命名导出时是否会发生树抖动?
- sqlbase - LONG VARCHAR - 从表读取到前面 (C#) 然后将值插入/更新到表
- javascript - 'app-element' 不是 Angular 中的已知元素
- r - R 中的 qnorm(0.05)
- mysql - MYSQL:排除同一天内重复的扫描日志
- javascript - 仅在屏幕场景和一个又一个元素中键入动画(jQuery)