鉴于我有两个 ES6 类。
这是A类:
import B from 'B';
class A {
someFunction(){
var dependency = new B();
dependency.doSomething();
}
}
B 类:
class B{
doSomething(){
// does something
}
}
我正在使用 mocha(对于 ES6 使用 babel)、chai 和 sinon 进行单元测试,效果非常好。但是在测试 A 类时如何为 B 类提供模拟类呢?
我想模拟整个 B 类(或所需的函数,实际上并不重要),这样 A 类就不会执行真正的代码,但我可以提供测试功能。
这就是 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???
});
});
最佳答案
您可以使用SinonJS 创建一个stub防止真正的功能被执行。
例如,给定A类:
import B from './b';
class A {
someFunction(){
var dependency = new B();
return dependency.doSomething();
}
}
export default A;
B 类:
class B {
doSomething(){
return 'real';
}
}
export default B;
测试可能如下所示:(sinon < v3.0.0)
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');
});
});
编辑:对于 sinon 版本 >= v3.0.0,使用这个:
describe("Class A", () => {
var InstanceOfA;
beforeEach(() => {
InstanceOfA = new A();
});
it('should call B', () => {
sinon.stub(B.prototype, 'doSomething').callsFake(() => 'mock');
let res = InstanceOfA.someFunction();
sinon.assert.calledOnce(B.prototype.doSomething);
res.should.equal('mock');
});
});
然后,如果需要,您可以使用 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.
关于javascript - 如何使用 mocha.js 模拟用于单元测试的依赖类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32695244/