Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lingo/d972e618b4f226866be2 to your computer and use it in GitHub Desktop.
Save lingo/d972e618b4f226866be2 to your computer and use it in GitHub Desktop.
var request = require('supertest-as-promised'),
Promise = require('bluebird'),
should = require('should');
var game = require('../game.js').app;
// Instead of assertScoreEquals, we now fetch the score
// and assert when the promise returns a value
var getScore = function() {
return request(game).get('/score').expect(200)
.then(function(res) {
result = res.body;
result.should.have.property('score');
return result.score;
});
};
// return the result (a promise) from supertest-as-promised
var roll = function(pins) {
return request(game).post('/bowl/' + pins);
};
// Build an array of promises
// and wait on them all with Promise.all
var rollMany = function(times, pins) {
var manyPromises = [];
for (var i = 0; i < times; i++) {
manyPromises.push(roll(pins))
}
return Promises.all(manyPromises);
};
// Make sure that beforeEach doesn't return until request is done
describe('Scoring a bowling game', function() {
beforeEach(function(done) {
request(game)
.get('/start')
.then(function() {
done(); // call the done callback when all is resolved
})
.catch(function(err) {
done(err); // pass the error back to mocha
})
.done(); // This 'done' is to finish the promise chain and make sure no thrown errors can possibly escape.
});
describe('gutter game', function() {
it('should return 0', function(done) {
rollMany(20,0) // wait on the promise returned
.then(function() {
return getScore(); // then fetch the score
})
.then(function(score) {
score.should.eql(0); // now assert the score is 0 as expected
done(); // tell Mocha the test is done
})
.catch(function(err) {
done(err); // tell Mocha the test failed with this error
})
.done(); // terminate the promise chain
});
});
. . .
@lingo
Copy link
Author

lingo commented Aug 11, 2014

Very welcome!

@neontapir
Copy link

So, when I try to run this using mocha, I get timeouts. Does that happen for you too?

@lingo
Copy link
Author

lingo commented Aug 20, 2014

I haven't actually run this code, sorry! However, with mocha, timeouts usually mean that a call to done is missing somewhere.

Basically, there should always be a call to done to terminate each test. If an error occurs (not including assertions) you can use done(error) to report that to mocha and terminate the test.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment