Idiomatically testing when.js promises with Jasmine

62 Views Asked by At

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?

2

There are 2 best solutions below

0
Steve Bennett On BEST ANSWER

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.

3
Benjamin Gruenbaum On

You should consider a testing library with promises support like Mocha, or using a helper like jasmine-as-promised which gives you this syntax. This would let you do something along the lines of:

// notice the return, and _not_ passing `done` as an argument to `it`:
return doMyThing().then(function(x) {
  expect(x).toEqual(42);
});

Basically, the return value is checked to be a promise and if it is the test framework checks if the promise rejected and treats that as a failure.