I am working on a unit test that is testing a generated parser code from a grammar. ( generated via PegJS) Im almost finished with most of the cases that are possible. There are 2-3 of them left and they are expected to throw an exception but i can't seem to figure out how to assert an exception.
(function () {
"use strict";
QUnit.module('durationTests');
QUnit.test('durationParseTest', function (assert) {
var dp1 = DurationParser.parse(new String('')); //this is the one that is expected to throw exception
var dp2 = DurationParser.parse(new String('P'));
var dp3 = DurationParser.parse(new String('P13MT2H'));
var dp4 = DurationParser.parse(new String('P2Y6M'));
assert.deepEqual(dp2,[]);
assert.deepEqual(dp3, [
{
"type": "M",
"val": 13
},
{
"type": "T"
},
{
"type": "H",
"val": 2
}
]);
there are many other cases but I included only these two to show how I tested them. They are working just fine right now.
The thing I don't get about QUnit throw assertion is that I don't know how to give the assertion this spesific parse function. Any help is appreciated.
Edit: I tried many of the suggested ways in QUnit website but still can't figure out how to test that spesific exception properly.
I managed to test the exception succesfully , im sharing the answer if anybody is interested
QUnit.test("Invalid string input throws SyntaxError", function (assert) {
assert.throws(
function () {
DurationParser.parse(new String(''));
},
function (error) {
return error.name === "SyntaxError";
}
);
});
QUnit website was not helpful at all, I figured it out by just trying different variations of this syntax.