I have a scenario where I want to make multiple REST calls to a Node.js service served by Express within a single test, namely:
var request = require('supertest'),
should = require('should'),
game = require('../game.js').app;
describe('single pin game of bowling', function(done) {
it('should return 20', function(done) {
for(var i = 0; i < 20; i++) {
request(game).post('/bowl/1').expect(200, function(){});
}
request(game).get('/score').expect('20', done);
});
});
At this stage, the POST call increments the value returned by /score
.
While this test passes, is there a way to eliminate the empty callback function in the POST expectation?
If I have no callback, score return 0 and the test fails. If I use done
as the callback, I get an error because done was called multiple times.
You say it works as shown, but when you remove the empty callback that it fails.
I think it shouldn't work with or without the callback because all those posts are asynchronous calls. You fire off 20 of them and immediately do a get. You have a race condition where you are getting lucky that the posts have finished before you do the get. (with the empty callback function you are winning this race condition, and without you are losing it.)
To fix the race condition, you need to wait for the posts to complete before doing the get for the score.
When a post (or get) request is completed the callback function is called. So the straight forward way is to fire off the first post, and then in its callback fire off the next post, or if it was the last fire off the get request.
Doing it that way is kind of nasty code and you may want to use promises instead. I searched a little and apparently there is an npm module called supertest-as-promised.