I'm writing some Jasmine unit tests for code that returns when.js promises. I keep finding myself writing code like this:
doMyThing().then(function(x) {
expect(x).toEqual(42);
done();
}).otherwise(function() {
expect(true).toBe(false);
done();
});
The only way to catch the exception is with the otherwise() function (it's an older version of when.js), and then there doesn't seem to be a Jasmine (2.0) function to say "failure detected" - hence the kludgy "expect(true).toBe(false)".
Is there a more idiomatic way of doing this?
After looking a bit more closely at the documentation and realising that we're using Jasmine 2.3, I see we can make use of the fail() function, which massively simplifies things. The example in the question becomes:
doMyThing().then(function(x) {
expect(x).toEqual(42);
}).otherwise(fail).then(done);
If doMyThing() throws an exception, that Error gets passed to fail() which prints a stack trace.
This .otherwise(fail).then(done); turns out to be a pretty convenient idiom.