mpasko256
mpasko256

Reputation: 841

Using Jasmine predefined matchers inside user defined one

I would like to define my custom, user defined matcher using Jasmine framework. I am going to verify a relation among two complex objects.

In example:

customMatchers = {
  toBeSiblings: function(util, customEqualityTesters) {
    return {
      compare: function(actual, expected) {
        expect(actual.parent).toBeDefined()
        expect(expected.parent).toBeDefined()
        result = {
          pass: util.equals(actual.parent, expected.parent, customEqualityTesters)
        };
        if (!result.pass) {
          result.message = "Expected object: " + actual + " to be sibling of: " + expected;
        }
        return result;
      }
    };
  }
};

I'd like to test some preconditions of compared objects using existing Karma matchers in a similar manner as in above example.

My question is: is it possible to extract matching result from used matcher to format proper message i.e. "Expected actual to has parent"?

Upvotes: 3

Views: 136

Answers (1)

hashchange
hashchange

Reputation: 7225

I just checked – turns out this is actually easy. Use the predefined matchers as you do in your example, and simply add a custom message to those matchers. The message doesn't replace the default message, but is appended to it.

expect(actual.parent).toBeDefined("or more precisely, expected object " + actual + " to have a parent");

In case of failure, you get a message of

Expected undefined to be defined 'or more precisely, expected object whatever to have a parent'.

Upvotes: 2

Related Questions