2017-05-31 157 views
0

在我參加TDD的旅程中,我使用了摩卡,柴和sinon。 那裏肯定有學習曲線。我如何測試摩卡咖啡的課程?

我的目標是編寫一個測試來驗證方法4是否已執行。我如何實現這一目標?

//MyData.js

class MyData { 

     constructor(input) { 
     this._runMethod4 = input; //true or false 
     this.underProcessing = this.init(); 
     }  

     method1() { return this.method2() } 

     method2() { 

     if (this._runMethod4) { 
      return this.method4(); 
     } else { 
     return this.method3(); 
     } 

     method4(){ 
     return thirdPartyAPI.getData(); 
     } 
     method3(){ 
     return someAPI.fetchData(); 
     } 

     init(){ 
     return this.method1(); 
     } 

    } 

MyData.spec.js

describe('MyData',() => { 

    it('should execute method 4', function() { 
     let foo = new MyData(true); 

     foo.underProcessing.then(()=>{ 
     // How do I verify that method4 was executed ?? 
     expect(foo.method4.callCount).to.equal(1); 
     }); 


    }); 
}) 

回答

1

下面是一個例子:

const expect = require('chai').expect; 
const sinon  = require('sinon'); 
const sinonTest = require('sinon-test'); 

sinon.test  = sinonTest.configureTest(sinon); 
sinon.testCase = sinonTest.configureTestCase(sinon); 

describe("MyData",() => { 
    it("should execute method 4", sinon.test(function() { 
    let spy = this.spy(MyData.prototype, 'method4'); 
    let foo = new MyData(true); 

    return foo.underProcessing.then(() => { 
     expect(spy.callCount).to.equal(1); 
    }); 
    })); 
}); 

作爲一個額外的要求,我說sinon-test,因爲它真的有助於在測試運行後幫助清理間諜/存根。

主要特徵是這一行:

let spy = this.spy(MyData.prototype, 'method4'); 

這由興農間諜,這是一個傳遞函數替換MyData.prototype.method4(所以它調用原來的),將記錄它是如何準確地叫,怎麼經常用什麼參數等等。你需要在實例創建之前這樣做,否則你太遲了(該方法可能已經通過在構造函數中以this.init()開頭的方法調用鏈調用)。

如果你想使用一個存根代替,這是不直通(這樣就不會調用原始的方法),你可以這樣做,以及:

let spy = this.stub(MyData.prototype, 'method4').returns(Promise.resolve('yay')); 

所以不是叫thirdPartyAPI.getData()的並返回結果現在將返回一個已解決的值爲yay的承諾。

其餘的代碼應該說明一切,需要注意的是:在foo.underProcessing.then(...)之前有明確的return

我認爲foo.underProcessing是一個承諾,所以它是異步的,這意味着你的測試也應該是異步的。由於Mocha支持承諾,因此當您從測試中返回承諾時,Mocha將知道如何正確處理它(還有一種使用Mocha製作asynchronous test的替代方法,涉及回調函數,但是當您測試基於承諾的代碼時不應該真的使用它們,因爲它很容易陷入超時或吞噬異常)。