Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test node data chunking function

I'm working on a project which uses node and we're trying to achieve 100% coverage of our functions. This is the only function we haven't tested, and it's within another function.

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

How do you go about testing this function? We tried exporting the function from another file but no luck.

I should mention that we are using tape as a testing module.

like image 587
Huw Davies Avatar asked Oct 22 '15 18:10

Huw Davies


2 Answers

You need to trigger this "data" event on req. So that this callback will be called.

For instance, let's suppose you have req on your test, you could do something like that (this is Mocha):

req.trigger('data', 'sampleData');
expect(userInput).to.equal('sampleData');
like image 105
Tiago Romero Garcia Avatar answered Oct 04 '22 05:10

Tiago Romero Garcia


req.emit('data', {sampleData: 'wrongOrRightSampleDataHere'}) should do it. When instantiating the http or hence the req object make sure you instantiate a new one, that no other test receives this event.

To be more complete...

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()
like image 43
eljefedelrodeodeljefe Avatar answered Oct 04 '22 05:10

eljefedelrodeodeljefe