How to test node data chunking function
Asked Answered
P

2

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.

Preoccupation answered 22/10, 2015 at 18:20 Comment(0)
S
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');
Scornik answered 22/10, 2015 at 18:29 Comment(2)
I should have mentioned that I'm using tape to test. Do you think it will work in a similar way regardless?Preoccupation
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 @eljefedelrodeodeljefeScornik
U
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()
Uzzia answered 22/10, 2015 at 18:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.