2016-08-03 2 views
0

プロシージャ内の特定のステップが実行されていることを確認するためにsinonを使用しようとしています。テストしているメソッドが指定された関数を呼び出すことを確認します。ここでsinonを使用して、メソッドが最終的に呼び出されるかどうかをテストする方法

は、私は現在、何をすべきかです:

describe('Native calls handling', function() { 

    var ctrl; 

    beforeEach(function() { 
     ctrl = new EthernetController($placeholder, notifications, null, nav); 
    }); 

    // What I currently do 
    it('Should perform internet check on `Connected` event', function(done) { 
     var errorTimeout = setTimeout(function() { 
      internetCheck.restore(); 
      done(new Error('Assertion failed, internetCheck was not executed')); 
     }, 1500); 

     var internetCheck = sinon.stub(ctrl, 'internetCheck', function() { 
      clearTimeout(errorTimeout); 

      internetCheck.restore(); 
      done(); 

      return Promise.resolve(true); 
     }); 

     app.notify('system:ethernet:connected'); 
    }); 

    // Functionality I'm looking for 
    it('Should perform internet check on `Connected` event', function(done) { 
     var internetCheck = sinon.stub(ctrl, 'internetCheck', function() { 
      return Promise.resolve(true); 
     }); 

     // Fail the test if the function is not called within $ ms 
     // Also restore the stub 
     internetCheck.cancelationTime = 1500; 

     // Trigger the assertion after/if the function is called 
     internetCheck.whenCalled(function(params...) {// assertion }) 
      .timedOut(done); 


     app.notify('system:ethernet:connected'); 
    }); 
}); 

Connectedイベントが最後にinternetCheck
私は

探しているものに似た何かがあるのを行います非同期手順をトリガします編集: 私の本当の問題は、使用されたメソッドが内部的に約束していたが、voidを返すので、手続きが完了したときにわかりやすい方法がない。 私はのNode.jsですthis solutionにつまずいてきた

答えて

0

をやってしまったものにとの回答を投稿します。私たちのプロジェクトはQの約束を使用していたので、私は自分自身を転がしました。

それは、sinonを必要としないが、それは私の問題を解決:

/** 
* Make testing of Q promises as synchronous code 
* Calling process.apply() will complete all pending Q promises 
*/ 
(function(global) { 
    'use strict'; 

    var _queue = []; 

    // Fake process object 
    global.process = { 
     // process.toString() is used internally by Q (v1.4.1) to recognize environment 
     // We are lying to it to exploit it's inner workings 
     toString: function() { 
      return '[object process]'; 
     }, 

     nextTick: function(cb) { 
      _queue.push(cb); 
     }, 

     apply: function() { 
      console.info('Flushing pending tasks'); 

      var head; 
      while (head = _queue.shift()) { 
       head(); 
      } 
     } 
    }; 

})(window); 

そして、テスト・ケース:

describe('Native calls handling', function() { 

    var ctrl; 

    beforeEach(function() { 
     ctrl = new EthernetController($placeholder, notifications, null, nav); 
    }); 

    it('Should perform internet check on `Connected` event', function() { 
     var internetCheck = sinon.stub(ctrl, 'internetCheck'); 
     internetCheck.returns(Q.resolve(true)); 

     app.notify('system:ethernet:connected'); 
     process.apply(); 

     expect(internetCheck).toHaveBeenCalled(); 
    }); 
}); 
関連する問題