Testing for exceptions with Jasmine

I just made a PR to the KaTeX library to help fix some cryptic error messages.

To do this I had a few places raise exceptions early instead of propagating deeply into the code before breaking in strange places with cryptic error messages. The library can _only_ deal with expressions that are strings so I added in this validation:

var render = function(expression, baseNode, options) {
    if (!(typeof expression === 'string' || expression instanceof String)) {
        throw new TypeError('render requires string typed expression');

    }

Naturally I wanted to make a test for this. Jasmine lets you check if an exception was thrown with the toThrowError. However I made a mistake when I first did this:

it("should throw TypeError when the expression is of the wrong type", function() {
    expect(katex.renderToString({badInputType: "yes"})).toThrowError(TypeError);
    expect(katex.renderToString(["foo", {badInputType: "yes"}])).toThrowError(TypeError);
});

See what went wrong?

The problem here is that the exception is thrown before expect can actually deal with it, therefore it slips out and fails the test case. To fix this you have to wrap your call in a function which Jasmine will invoke from within expect:

it("should throw TypeError when the expression is of the wrong type", function() {
    expect(function() {
        katex.renderToString({badInputType: "yes"});
    }).toThrowError(TypeError);
    expect(function() {
        katex.renderToString(["foo", {badInputType: "yes"}]);
    }).toThrowError(TypeError);
});

blogroll

social