2015-09-21 32 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