如何testing节点数据分块function

我正在开发一个使用节点的项目,我们正在努力实现我们function的100%覆盖。 这是我们没有testing过的唯一function,而且是另一个function。

var userInput = ""; req.on("data", function(data){ userInput += data; }); 

你如何去testing这个function? 我们尝试从另一个文件导出function,但没有运气。

我应该提到,我们正在使用磁带作为testing模块。

你需要在req上触发这个“data”事件。 所以这个callback将被调用。

例如,假设你对testing有要求,你可以这样做(这是摩卡):

 req.trigger('data', 'sampleData'); expect(userInput).to.equal('sampleData'); 

req.emit('data', {sampleData: 'wrongOrRightSampleDataHere'})应该这样做。 当实例化httpreq对象时,确保你实例化一个新的,没有其他testing收到这个事件。

要更完整…

 var assert = require('assert') function test() { var hasBeenCalledAtLeastOnce = false var userInput = ""; // req must be defined somewhere though req.on("data", function(data){ userInput += data; if(hasBeenCalledAtLeastOnce) { assert.equal(userInput, "HelloWorld", "userInput is in fact 'HelloWorld'") } hasBeenCalledAtLeastOnce = true }); req.emit('data', "Hello") req.emit('data', "World") } test()