2017-09-19 19 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을 사용하여 방출해야합니다. 둘째, someModule.getStuff (...) 메서드 호출 직후에 이벤트를 내 보내야합니다.

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

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

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