-
-
Save thanpolas/5367556 to your computer and use it in GitHub Desktop.
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'); |
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:
test('an async test with a promise', function(done){
function onResolve(obj) {
return obj.prom.then(function(val){
assert.equal('bar', val, 'Value should be "bar"');
});
}
getProm().then(onResolve).then(done, done);
});
The key is the added return
inside onResolve
, and adding the then(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 :)
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?
I didn't know that mocha/chai-as-promised supported returning promises from tests, or at least that's what I gather from your latest example @domenic. We love that feature of BusterJS, so it's nice to see other unit test platforms support it too.
@thanpolas: Glad you have a working solution!