2015-09-21 33 views
20

鉴于我有两个ES6类。如何模拟mocha.js单元测试的依赖类?

这是A类:

import B from 'B'; 

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

和B类:

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

我用摩卡(与巴别塔的ES6)单元测试,湾仔及兴农,其中真正伟大的作品。但是在测试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??? 
    }); 
}); 
+0

阅读[DI](https://en.wikipedia.org/wiki/Dependency_injection) – Mritunjay

回答

20

您可以使用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",() => { 

    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();

var stub = sinon.stub(object,“method”);
用 存根函数替换object.method。原始功能可通过拨打 object.method.restore();(或stub.restore();)进行恢复。如果该属性不是一个函数,则抛出异常 ,以帮助避免在存在 存根方法时发生错别字。

+0

Woa。那很简单。没有想到改变原型。谢谢! :)你有关于如何嘲笑构造函数的提示?似乎不以同样的方式工作? – mvmoay

+1

检查这个答案我给了几天前http://stackoverflow.com/questions/32550115/mocking-javascript-constructor-with-sinon-js/32551410#32551410 – victorkohl

+0

你会怎么做这个B的构造函数? – Willwsharp