Promises you can trust
{ | |
"name": "promises", | |
"scripts": { | |
"test": "node node_modules/mocha/bin/mocha --watch --growl" | |
}, | |
"devDependencies": { | |
"chai": "^1.10.0", | |
"mocha": "^2.0.1" | |
}, | |
"dependencies": { | |
"q": "^1.1.2" | |
} | |
} |
var Q = require('q'); | |
var expect = require('chai').expect; | |
describe('promises', function() { | |
it('can be resolved', function(done) { | |
var promise = Q.Promise(function(resolve) { | |
resolve(); | |
}); | |
promise.then(function() { | |
done(); | |
}); | |
}); | |
it('can pass resolution value', function(done) { | |
var promise = Q.Promise(function(resolve) { | |
resolve(6*7); | |
}); | |
promise.then(function(value) { | |
expect(value).to.equal(42); | |
}).done(done); | |
}); | |
it('can return the promise to mocha', function() { | |
var promise = Q.Promise(function(resolve) { | |
resolve(6*7); | |
}); | |
return promise.then(function(value) { | |
expect(value).to.equal(42); | |
}); | |
}); | |
it('can pass values in a promise chain', function(done) { | |
var promise = Q.Promise(function(resolve) { | |
resolve(6); | |
}); | |
promise.then(function(v) { | |
return v*7; | |
}).then(function(v) { | |
expect(v).to.equal(42); | |
}).done(done); | |
}); | |
it('can resolve multiple promises', function(done) { | |
var promise = Q.Promise(function(resolve) { | |
resolve(['abc', 'def', 'gh']); | |
}); | |
promise.then(function(array) { | |
return Q.all(array.map(function(v) { | |
return Q.Promise(function(resolve) { | |
resolve(v.length); | |
}) | |
})); | |
}).then(function(lengthArray) { | |
expect(lengthArray).to.eql([3,3,2]); | |
}).done(done); | |
}); | |
it('can reject a promise', function(done) { | |
var promise = Q.Promise(function(resolve, reject) { | |
reject('something went wrong'); | |
}); | |
promise.fail(function(error) { | |
expect(error).to.equal('something went wrong'); | |
}).done(done); | |
}); | |
it('treats errors as rejections', function(done) { | |
var promise = Q.Promise(function(resolve, reject) { | |
resolve(null); | |
}); | |
promise.then(function(value) { | |
return value.length; | |
}).fail(function(error) { | |
expect(error.message).to.eql("Cannot read property 'length' of null"); | |
}).done(done); | |
}); | |
it('propagates failure to the first failure handler', function(done) { | |
var promise = Q.Promise(function(resolve, reject) { | |
resolve(null); | |
}); | |
promise.then(function(value) { | |
return value.length; // Throws Error | |
}).then(function(length) { | |
this.test.error("never called"); | |
}).then(function(number) { | |
this.test.error("never called"); | |
}).fail(function(error) { | |
expect(error.message).to.eql("Cannot read property 'length' of null"); | |
}).done(done); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment