0

I have an odd looking test spec below.

expect(function(){
   expect(null).not.toEqualMoment(testContext.moment1);
}).toThrow();

The inner expectation fails because of the check below inside my custom matcher, which throws an exception.

if(!moment.isMoment(actual)) {
    throw new Error(_.string.sprintf('Actual: %s , is not a Moment object.', jasmine.pp(actual)));
}

I think an exception has to be thrown here and not just return a failing result because if not, expect(null).not.toEqualMoment(null) will return true. ( If that makes sense to you ) .

So, If I fail custom matchers with exceptions, how can I test this?

Jesse
  • 1,673
  • 1
  • 16
  • 22

1 Answers1

0

If you want to test your custom matcher, several problems occur when you do this by just apply your matchers. For most simple custom matchers, you can just do expect(actual).toBeCustom(expected). If the test passes, the matcher is ok. For the inverted case, just add .not.

However, in this way you are not testing the internal workings of the matcher, like what message is returned when a matcher fails, or - in your case - that the matcher throws and exception. You tried to test this by nesting expect calls, which is not possible.

Therefore, you need to add the matcher itself to your test and test the compare method.

expect(toEqualMomentMatcher.compare({}, momentjs())).toThrow('Actual: Object({ }) is not a Moment object');

Apart from your question, I advice you to let the matcher fail if actual is not a Moment. Just return a different message when actual is not a Moment.

Frank van Wijk
  • 3,234
  • 20
  • 41