Try / catch jasmine

I have a function that tries to parse a parameter as a JSON object. If this fails, backup is used instead.

parsing-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 do not see any problems in this code. However, when I try to add some unit tests (using Jasmine 2.3) for the "catch" case, Jasmine catches the JSON parsing error on its own and aborts the test:

For example, for the Jasmine test, for example:

 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 with throw Error(...) , but finally this is not suitable for my case. Any suggestions on how to use jasmine in this case?

+5
source share
2 answers

You cannot call a function yourself, you must let Jasmine call it by adding a wrapper function. Another way to explain this is that expect needs a function passed to it when you test it to quit.

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

On your page, note that the function is passed 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"); }); 
+7
source

Have you tried wrapping a given fn? Thus, jasmine will be able to execute it on its own and provide additional code to catch it.

 describe("usingJSONFallback", function() { it("should throw an error if it called with a string", function() { expect(function () { usingJSONFallback("any string"); }).toThrow(); }); }); 
+3
source

Source: https://habr.com/ru/post/1236057/


All Articles