如何模拟mocha.js进行unit testing的依赖类?

鉴于我有两个ES6类。

这是A类:

import B from 'B'; class A { someFunction(){ var dependency = new B(); dependency.doSomething(); } } 

和B类:

 class B{ doSomething(){ // does something } } 

我使用摩卡进行unit testing(与ES6的babel),柴和sinon,这真的很棒。 但是在testingA类时,我怎样才能为B类提供一个模拟类?

我想嘲笑整个B类(或所需的function,实际上并不重要),以便类A不执行真正的代码,但我可以提供testingfunction。

这就是摩卡testing现在的样子:

 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创build一个存根,以防止执行实际function。

例如,给定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; 

testing可能看起来像:

 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'); }); }); 

然后你可以使用object.method.restore();来恢复函数object.method.restore();

var stub = sinon.stub(object,“method”);
用存根函数replaceobject.method。 原函数可以通过调用object.method.restore();来恢复object.method.restore(); (或者stub.restore(); )。 如果该属性不是一个函数,则抛出exception,以帮助在存根方法时避免拼写错误。