Skip to content

Instantly share code, notes, and snippets.

@verma
Created November 27, 2013 23:38
Show Gist options
  • Save verma/7684962 to your computer and use it in GitHub Desktop.
Save verma/7684962 to your computer and use it in GitHub Desktop.
Helpers functions for promises based unit testing
// testq.js
// Test Q based functions
//
var Q = require('q');
var asQ = function(f) {
return function(test) {
f(test).fin(function() {
test.done();
}).done();
};
};
var rejects = function(f) {
return asQ(function(test) {
return f(test).then(function() {
test.ok(false, "Should reject");
}).catch(function() {
test.ok(true, "Should reject");
});
});
};
var accepts = function(f) {
return asQ(function(test) {
return f(test).then(function() {
test.ok(true, "Should accept");
}).catch(function() {
test.ok(false, "Should accept");
});
});
};
var doLater = function(throwError) {
var d = Q.defer();
setTimeout(function() {
if (throwError)
return d.reject(new Error('You messed up'));
d.resolve({ result: 'I got you' });
}, 300 + Math.floor(Math.random() * 700));
return d.promise;
}
exports.tests = {
testManual: asQ(function(test) {
return doLater().then(function(res) {
test.ok(res.value !== undefined, 'Value should not be undefined');
});
}),
testCheckRejects: rejects(function(test) {
return doLater(true);
}),
testCheckAccepts: accepts(function(test) {
return doLater();
}),
testCheckAcceptsButFails: accepts(function(test) {
return doLater(true);
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment