Javascript 如何使用 mocha.js 模拟用于单元测试的依赖类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32695244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to mock dependency classes for unit testing with mocha.js?
提问by mvmoay
Given that I have two ES6 classes.
鉴于我有两个 ES6 类。
This is class A:
这是A类:
import B from 'B';
class A {
someFunction(){
var dependency = new B();
dependency.doSomething();
}
}
And class B:
B类:
class B{
doSomething(){
// does something
}
}
I am unit testing using mocha (with babel for ES6), chai and sinon, which works really great. But how can I provide a mock class for class B when testing class A?
我正在使用 mocha(ES6 的 babel)、chai 和 sinon 进行单元测试,效果非常好。但是,在测试 A 类时,如何为 B 类提供模拟类?
I want to mock the entire class B (or the needed function, doesn't actually matter) so that class A doesn't execute real code but I can provide testing functionality.
我想模拟整个 B 类(或所需的功能,实际上并不重要),以便 A 类不执行真正的代码,但我可以提供测试功能。
This is, what the mocha test looks like for now:
这就是 mocha 测试现在的样子:
var A = require('path/to/A.js');
describe("Class A", () => {
var InstanceOfA;
beforeEach(() => {
InstanceOfA = new A();
});
it('should call B', () => {
InstanceOfA.someFunction();
// How to test A.someFunction() without relying on B???
});
});
采纳答案by victorkohl
You can use SinonJS to create a stubto prevent the real function to be executed.
您可以使用 SinonJS 创建一个存根来阻止真正的函数被执行。
For example, given class A:
例如,给定 A 类:
import B from './b';
class A {
someFunction(){
var dependency = new B();
return dependency.doSomething();
}
}
export default A;
And class B:
B类:
class B {
doSomething(){
return 'real';
}
}
export default B;
The test could look like:
测试可能如下所示:
describe("Class A", () => {
var InstanceOfA;
beforeEach(() => {
InstanceOfA = new A();
});
it('should call B', () => {
sinon.stub(B.prototype, 'doSomething', () => 'mock');
let res = InstanceOfA.someFunction();
sinon.assert.calledOnce(B.prototype.doSomething);
res.should.equal('mock');
});
});
You can then restore the function if necessary using object.method.restore();
:
如有必要,您可以使用object.method.restore();
以下命令恢复该功能:
var stub = sinon.stub(object, "method");
Replaces object.method with a stub function. The original function can be restored by callingobject.method.restore();
(orstub.restore();
). An exception is thrown if the property is not already a function, to help avoid typos when stubbing methods.
var stub = sinon.stub(object, "method");
用存根函数替换 object.method。可以通过调用object.method.restore();
(或stub.restore();
)恢复原始功能 。如果该属性还不是函数,则会引发异常,以帮助避免在存根方法时出现拼写错误。