Last active
February 9, 2016 12:40
-
-
Save lingo/d972e618b4f226866be2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}); | |
}); | |
. . . |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 usedone(error)
to report that to mocha and terminate the test.