Jasmine throws an error while waiting (). ToThrow instead of identifying a thrown error

I am trying to implement functions for printing diamond in terms of test-based learning 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 with error handling. The above function 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 also tried an anonymous function while waiting (..), but that also didn't work.

Console message: The expected function to reset is "Inval ...", but it throws an error: invalid combination of arguments.

I do not understand what to do with this information.

Edit: This is strange because it works with Jasmine v.1.3, but it did not work with jasmine v.2.3 ie or with karma, although the code is based on jasmine.

+7
javascript tdd karma-runner jasmine karma-jasmine
source share
1 answer

TL; DR

With Jasmine 2, the semantics of the sample changed and a new coincidence appeared.

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

NTL; TR

Since Jasmine 2.x is the new Matcher toThrowError() , and Jasmine toThrow() become the new semantics.

  • toThrow() should be used to check if any error has been selected or to check the Error message (more specific: someting that instanceof Error )
  • toThrowError() should be used to check if a specific error has been selected or if the error message is equal to waiting

Inside toThrow(x) , it checks for the equality of the discarded error with x . If both the error and x are equal to instanceof Error (which is also true for TypeError ), Jasmine checks the equality ( === in general) of the message side attributes.

The toThrowError(x) form checks if the error message is equal to or matches x (string or RegExp)

Another form of toThrowError(t, x) checks if an error is of type t , and the message is equal to or matches x (string or RegExp)

Cm

+9
source share

All Articles