jeudi 25 décembre 2014

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? What is the best practice to obtain the target behavior given these tools?





Aucun commentaire:

Enregistrer un commentaire