Skip to content

Hamjest and Promises

David Orlea edited this page Mar 9, 2016 · 1 revision

Promising matchers

If a matcher cannot test a value immediately, its match methods may return a promise instead of a boolean value. Such matchers are called promising matchers and may only be used with promiseThat.

The promise returned by match should eventually resolve with a truthy value if the tested value could be matched, otherwise it should resolve with a falsy value. The promise should only be rejected if a technical error (eg. an exception) occurs. See the implementation of willBe for an example.

A promising matcher may also return a promise from its describeMismatch method if describing the mismatch is an asynchronous operation. The promise should be resolved as soon as the description is complete.

Promise-aware matchers

All matchers that accept sub-matchers (eg. allOf, not, contains, ...) accept promising matchers and become promising matchers themselves if at least one of the provided matchers is a promising matcher.

Attention: There's currently one exception to this rule: containsInAnyOrder does NOT support promising matchers because its implementation is already pretty complicated without this and the use case was not required so far. Open an issue or submit a pull request if you need this feature.

promiseThat

You may use promiseThat(value, matcher) instead of assertThat(value, matcher) whenever you need to use a promising matcher. (It also accepts normal matchers.)

promiseThat returns a promise that will be fulfilled if the matcher matchers the given value. The promise will be rejected with an assertion error if the matcher does not match.

You can use promiseThat with promise-aware testing frameworks such as mocha or Jasmine 2.x (not Jasmine 1.x) by simply returning the result:

...
it('should eventually resolve', function () {
    var result = someMethodThatReturnsAPromise();
    return __.promiseThat(result, __.is(__.fulfilled())));
});

it('should eventually be rejected', function () {
    var result = someMethodThatReturnsAPromise();
    return __.promiseThat(result, __.is(__.rejected())));
});

it('should resolve with "fulfillment value"', function () {
    var result = someMethodThatReturnsAPromise();
    return __.promiseThat(result, __.willBe('fulfillment value'));
});
...

The tests will wait until promiseThat resolves and will display the appropriate assertion error if the matcher fails.

Clone this wiki locally