Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try/catch with jasmine

I have a function which tries to parse a parameter as a JSON object. If it failed, it uses a fallback instead.

parse-code.js

function parseCode(code) {
    try {
        usingJSONFallback(code);
    } catch() {
        usingStringFallback(code);
    }
}

function usingJSONFallback(code) {
    JSON.parse(code);
    //...more code here
}

function usingStringFallback(code) {
   //... more code here
}

main.js

//Some code...
parseCode('hello world!');

I'm not seeing any issue in this code. However, when I'm trying to add some unit tests (using Jasmine 2.3) for the 'catch' case, Jasmine catches the JSON parsing error by its own and abort the test:

For instance, for a Jasmine test like:

describe('parseCode', function() {
    it('Parses a string', function() {
        var code = 'My code without JSON';
        expect(parseCode(code)).toThrow();
    });
});

or even a test like:

describe('usingJSONFallback', function() {
   it('Throw an error if there is a string', function() {
      var code = 'My code without JSON';
      expect(usingJSONFallback(code)).toThrow();
   });
});

In both cases, the test fails and returns:

SyntaxError: Unable to parse JSON string

I read about throwing controlled exceptions using throw Error(...), but definitively this doesn't fit well for my case. Any suggestions about how to use Jasmine in this case?

like image 714
fcortes Avatar asked Nov 16 '15 14:11

fcortes


2 Answers

You can't call the function yourself, you have to let Jasmine call it by adding a wrapper function. Another way to explain it is that expect needs a function passed to it when you are testing for it to throw.

describe('parseCode', function() {
    it('Parses a string', function() {
        var code = 'My code without JSON';
        expect(function() { parseCode(code) }).toThrow();
    });
});

From their example page, notice that the function is passed in but not called.

it("The 'toThrowError' matcher is for testing a specific thrown exception", function() {
    var foo = function() {
      throw new TypeError("foo bar baz");
    };

    expect(foo).toThrowError("foo bar baz");
    expect(foo).toThrowError(/bar/);
    expect(foo).toThrowError(TypeError);
    expect(foo).toThrowError(TypeError, "foo bar baz");
  });
like image 101
Juan Mendes Avatar answered Sep 23 '22 18:09

Juan Mendes


Have you tried wrapping the given fn? This way jasmine will be able to execute it on its own and provide extra code to catch it.

describe("usingJSONFallback", function() {

    it("should throw an error if it's called with a string", function() {

        expect(function () {
            usingJSONFallback("any string");
        }).toThrow();

    });

});
like image 31
Emil A. Avatar answered Sep 19 '22 18:09

Emil A.