Lars Kemmann
Lars Kemmann

Reputation: 5674

Failing an asynchronous test case using promises

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

Answers (1)

Lars Kemmann
Lars Kemmann

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

Related Questions