Created
April 11, 2013 22:00
-
-
Save thanpolas/5367556 to your computer and use it in GitHub Desktop.
Testing promises with mocha
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 assert = require('chai').assert; | |
var when = require('when'); | |
var def1 = when.defer(); | |
function getProm() { | |
return def1.promise; | |
} | |
suite('Test a promise', function() { | |
test('an async test with a promise', function(done){ | |
function onResolve(val) { | |
assert.equal('bar', val, 'Value should be "bar"'); | |
done(); | |
} | |
// the trick is the final .otherwise that will catch | |
// the error thrown in the 'onResolve' function | |
getProm().then(onResolve, done).otherwise(done); | |
}); | |
}); | |
def1.resolve('foo'); |
wouldnt be cool to adopt the given-when-then of BDD into mocha with something like this:
it('test', function(){
return given().when().then()
});
does anybody know what I am talking about?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In case you don't want to return a promise or find a reason that you can't, then, if you preserve the promise chain by returning promises from inside handlers, you'll likely only need
.then(done, done)
at the end of the chain, since any thrown exception will be translated into a rejection and will propagate through the chain. Here's a refactor of one of your earlier examples, @thanpolas:The key is the added
return
insideonResolve
, and adding thethen(done, done)
to the end of the promise chain. I fully admit that I haven't tried this in mocha, but we do it all the time in BusterJS, and just knowing how promise error propagation works, I can't see why this wouldn't be equivalent.EDIT: Oops: probably need .then(done, done) in this case since
done()
needs to be called regardless of promise outcome. This isn't as nice as being able to return promises, though :)