JivanAmara
JivanAmara

Reputation: 1115

How do I reuse a test function with async calls in nodejs?

I'm new to node.js and it's been a while since I've worked with an asynchronous framework. In a procedural language such as python it's easy to have a list of inputs and expected outputs then to loop through them to test:

tests = {
  1: [2, 3],
  2: [3, 4],
  7: [8, 9],
}

for input, expected_out in tests.items():
  out = myfunc(input)
  assert(out == expected_out)

I'm attempting to do something similar with nodejs/mocha/should:

var should = require('should');

function myfunc(x, cb) { var y = x + 1; var z = x + 2; cb([y, z]); };

describe('.mymethod()', function() {
    this.timeout(10000);
    it('should return the correct output given input', function(done) {
        var testCases = {
                1: [2, 3],
                2: [3, 4],
                7: [8, 9],
            };

        for (input in testCases) {
            myfunc(input, function (out) {
                var ev = testCases[input];
                out.should.equal(ev);
            });
        }
    })
})

This results in:

  AssertionError: expected [ '11', '12' ] to be [ 2, 3 ]
  + expected - actual

   [
  +  2
  +  3
  -  "11"
  -  "12"
   ]

I have no idea where [ '11', '12' ] comes from, but it smacks of a thread safety issue.

Can anyone explain to me where these unexpected values are coming from?

Upvotes: 2

Views: 166

Answers (1)

Kelsadita
Kelsadita

Reputation: 1038

It seems that the input you are passing to myfunc is being considered as String. Have a look at this answer.

Keys in Javascript objects can only be strings?

Try this,

var should = require('should');

function myfunc(x, cb) { var y = x + 1; var z = x + 2; cb([y, z]); };

describe('.mymethod()', function() {
    this.timeout(10000);
    it('should return the correct output given input', function(done) {
        var testCases = {
            1: [2, 3],
            2: [3, 4],
            7: [8, 9],
        };

        for (input in testCases) {
            input = parseInt(input)
            myfunc(input, function (out) {
                var ev = testCases[input];
                out.should.equal(ev);
            });
        }
    })
})

Here, I have parsed the input to its integer value.

Upvotes: 3

Related Questions