2017-09-19 4 views
0

なぜこれが動作しないのか、私の頭を浮かべることはできません。ネイティブのnodejs httpモジュールを使用して、いくつかのペイロードを含むHTTP POSTリクエストを送信するモジュールがあります。私はsinonで要求メソッドをスタブし、要求ストリームと応答ストリームに対してPassThroughストリームを渡します。ストリーム終了時にコールバックスパイが呼び出されない

DummyModule.js

const http = require('http'); 

module.exports = { 

    getStuff: function(arg1, arg2, cb) { 

     let request = http.request({}, function(response) { 

      let data = ''; 

      response.on('data', function(chunk) { 
       data += chunk; 
      }); 

      response.on('end', function() { 
       // spy should be called here 
       cb(null, "success"); 
      }); 

     }); 


     request.on('error', function(err) { 
      cb(err); 
     }); 

     // payload 
     request.write(JSON.stringify({some: "data"})); 
     request.end(); 
    } 

}; 

test_get_stuff.js

const sinon = require('sinon'); 
const http = require('http'); 
const PassThrough = require('stream').PassThrough; 

describe('DummyModule', function() { 

    let someModule, 
     stub; 

    beforeEach(function() { 
     someModule = require('./DummyModule'); 
    }); 

    describe('success', function() { 

     beforeEach(function() { 
      stub = sinon.stub(http, 'request'); 

     }); 

     afterEach(function() { 
      http.request.restore() 
     }); 

     it('should return success as string', function() { 
      let request = new PassThrough(), 
       response = new PassThrough(), 
       callback = sinon.spy(); 

      response.write('success'); 
      response.end(); 


      stub.callsArgWith(1, response).returns(request); 

      someModule.getStuff('arg1', 'arg2', callback); 

      sinon.assert.calledWith(callback, null, 'success'); 
     }); 
    }); 
}); 

スパイが呼び出されません。また、テストがAssertError: expected spy to be called with argumentsで失敗します。したがって、response.on('end', ...)は呼び出されないため、テストに失敗します。応答ストリームの終了イベントは何とかトリガーされる必要がありますか?

答えて

0

これで動作します。まず、イベントを発行するには、methodのemitを使用する必要があります。 第2に、someModule.getStuff(...)メソッド呼び出しの直後にイベントを送出する必要があります。

... 
someModule.getStuff('arg1', 'arg2', callback); 

response.emit('data', 'success'); 
response.emit('end'); 

sinon.assert.calledWith(callback, null, 'success'); 
... 
関連する問題