2017-05-31 10 views
0

私はTDDに向かう途中で、モカ、チャイ、スロンを使用しています。 そこには学習曲線があります。モカのクラスをテストするには?

私の目標は、method4が実行されたことを確認するためのテストを作成することです。どのように達成するのですか?

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

これは、パススルー機能であるSinonスパイによるMyData.prototype.method4を置き換える(それは元を呼び出す)が呼び出されたかを正確に記録することになるよう、どのように多くの場合、どのような引数などが必要です。インスタンスが作成される前にこれを行う必要があります。それ以外の場合は遅すぎます(メソッドは、コンストラクタでthis.init()で始まるメソッド呼び出しの連鎖を通じて既に呼び出されている可能性があります)。

あなたはパススルーではない(それは、元のメソッドを呼び出すことはありません)、あなたにもそれを行うことができますされており、代わりにスタブを使用したい場合:

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

ので、代わりのthirdPartyAPI.getData()を呼び出しますその結果を返すとは値yayで解決された約束を返します。

残りのコードは、1つの注意点があります:foo.underProcessing.then(...)の前に明示的なreturnがあります。

私はfoo.underProcessingが約束だと思うので、非同期です。つまり、テストも非同期でなければなりません。 Mochaは約束を支持しているので、テストから約束を得ると、Mochaは適切に対処する方法を知っています(コールバック関数を含む、Mochaでasynchronous testを作成する別の方法がありますが、約束ベースのコードをテストしているときタイムアウトや飲み込まれた例外に遭遇しやすいので、実際にはそれらを使用すべきではありません。

関連する問題