6

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.

Huw Davies
  • 791
  • 7
  • 19

2 Answers2

1

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');
Tiago Romero Garcia
  • 1,068
  • 9
  • 11
  • I should have mentioned that I'm using tape to test. Do you think it will work in a similar way regardless? – Huw Davies Oct 23 '15 at 09:18
  • 1
    Yes I think it would. Can you please test the following: ```req.emit('data', 'sampleData'); console.log(userInput);``` and see if it prints 'sampleData' - otherwise try the suggestion from @eljefedelrodeodeljefe – Tiago Romero Garcia Oct 23 '15 at 16:57
1

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()
eljefedelrodeodeljefe
  • 6,304
  • 7
  • 29
  • 61