Reputation: 5674
I'm starting to use Jasmine for unit-testing of a JavaScript library that relies heavily on promises. I need to fail a test case asynchronously, and would like to write something like the following:
describe("An async test suite", function () {
it("should fail asynchronously", function (done, fail) {
var promise = myLibraryCall();
promise.then(done, function(reason) { fail(reason); });
});
});
However, there is nothing like a fail
call available from what I can see. And I can't throw an exception in the asynchronous error case because it's not caught by Jasmine - all I get is an eventual generic timeout. What is the best way to address this?
Upvotes: 1
Views: 105
Reputation: 5674
Short of modifying Jasmine itself, the simple solution is to create a wrapper around a combination of expect
and a custom matcher to fail with a given message.
function endTestAfter(promise, done) {
var customMatchers = {
toFailWith: function () {
return {
compare: function (actual, expected) {
return {
pass: false,
message: "Asynchronous test failure: " + JSON.stringify(expected)
};
}
}
}
};
jasmine.addMatchers(customMatchers);
promise.done(done, function (reason) {
expect(null).toFailWith(reason);
done();
});
}
This yields the following test suite code:
describe("An async test suite", function () {
it("should fail asynchronously", function (done, fail) {
var promise = myLibraryCall();
endTestAfter(promise, done);
});
});
Upvotes: 1