0

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?

Steve Bennett
  • 114,604
  • 39
  • 168
  • 219

2 Answers2

2

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.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • Ok, that's helpful to know. Are you implicitly saying there's no way to do anything nicer without a helper library like that? – Steve Bennett Sep 07 '15 at 07:19
  • You can write short helpers, but I'd just use the modern approach rather than reinvent wheels. Then again I'd probably write tests with babel and use async/await which would make for even nicer syntax. – Benjamin Gruenbaum Sep 07 '15 at 07:21
  • 1
    Yeah. Well there's always a better way of doing whatever we're doing :) Anyway it's not my codebase, so I'm certainly not making any big changes like that. – Steve Bennett Sep 07 '15 at 07:27
0

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.

Steve Bennett
  • 114,604
  • 39
  • 168
  • 219