没有在SO或网络上找到解决方案,希望有人能帮助我.
鉴于我有两个ES6课程.
这是A类:
import B from 'B'; class A { someFunction(){ var dependency = new B(); B.doSomething(); } }
和B类:
class B{ doSomething(){ // does something } }
我使用mocha进行单元测试(用于ES6的babel),chai和sinon,它们的效果非常好.但是,当测试A类时,如何为B类提供一个模拟类?
我想模拟整个类B(或所需的函数,实际上并不重要),因此A类不执行实际代码,但我可以提供测试功能.
这就是摩卡考试现在的样子:
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;
测试可能如下所示:
describe("Class A",() => { sinon.stub(B.prototype,'doSomething',() => '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 calling
object.method.restore();
(orstub.restore();
). An exception is thrown if the property is not already a function,to help avoid typos when stubbing methods.