Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jasmine throws error on expect().toThrow instead of identifying the thrown error

I'm trying to implement functions for printing a diamond in terms of learning test driven development in javascript.

Diamond.prototype.outerSpace = function (current, widest) {

  var currentValue = this.getIndexOf(current);
  var widestValue = this.getIndexOf(widest);

  if (currentValue > widestValue) {
      throw new Error('Invalid combination of arguments');
  }

  var spaces = widestValue - currentValue;
  return new Array(spaces + 1).join(' ');
};

I have problems in Error handling. The function above should throw an error, if currentValue is greater than widestValue.

This is my snippet representing the test/spec:

it ("should throw an exception, if it is called with D and C", function () {
    var outerSpace = diamond.outerSpace.bind(diamond, 'D', 'C');
    expect(outerSpace).toThrow('Invalid combination of arguments');
});

I've tried also with an anonymous function in expect(..), but this also didn't work.

The Console message is: Expected function to throw 'Inval...' but it throw Error: Invalid combination of arguments.

I don't get it, what I should do with this information.

Edit: It is strange, because it is working with Jasmine v.1.3, but it didnt work with jasmine v.2.3 i.e. or with karma, although the code based on jasmine.

like image 854
Texas Avatar asked Nov 22 '15 14:11

Texas


1 Answers

TL;DR

With Jasmine 2 the matchers semantics changed and there's a new matcher.

Use toThrowError("<message>") or toThrow(new Error("<message>")))

NTL;TR

Since Jasmine 2.x there is a new Matcher toThrowError() and Jasmine's toThrow() got a new semantic.

  • toThrow() should be used to check if any error was throw or to check for the message of an Error (more concrete: someting that's instanceof Error)
  • toThrowError() should be used to check if a specific error was thrown or if the message of the error equals the expectation

Internally toThrow(x) makes an equality check of the thrown error against x. If both the error and x are instanceof Error (which would be true for TypeError too for example) Jasmine checks equality (=== in general) of both sides message attributes.

The form toThrowError(x) checks whether the error message equals or matches x (string or RegExp)

The other form toThrowError(t, x) checks whether the error is of type t and message equals or matches x (string or RegExp)

See

  • Jasmine 2.3 Included Matchers (Examples at the end of the block)
  • Source of toThrow()
  • Source of toThrowError()
like image 186
try-catch-finally Avatar answered Sep 26 '22 09:09

try-catch-finally