Question

I have some JSON data inside of an HTML data element:

<div id="ps-data" data-ps="
        {
            "teacherId": 12345678
        },
"></div>

I parse it using jQuery's parseJSON function, but if I pass it invalid JSON, I get a SyntaxError exception. In QUnit, this shows up as a global failure, but I'd like it to fail in one of my test cases. What's the best way to do so?

My parsing code looks like:

$.parseJSON($('#ps-data').data().ps);
Was it helpful?

Solution

You could do something like this:

var exeptionReached = false;
try {
    $.parseJSON($('#ps-data').data().ps);
} catch(e) {
    exceptionReached = true;
}
console.log(exceptionReached); //will be true if `parseJSON()` threw an exception

Use qunit to assert exception was reached... or you can save something from the exception object if you want to assume something specific about it, for example:

var ex;
try {
    $.parseJSON($('#ps-data').data().ps);
} catch(e) {
    ex = e;
}
console.log(ex.message); // something like "Unexpected token ,"

You'll want to check that ex is defined before accessing properties of course. I think you should be able to see how you can test whether or not an exception happened and how to test specifics about that exception if you want... but let me know if you have any extra questions.

JSFiddle example

OTHER TIPS

Here's the full example of what I'm doing based on smerny's answer.

function testParse() {
    var exceptionMsg;
    try {
        var data = $j.parseJSON($j('#ps-data').data().ps);
    } catch (e) {
        exceptionMsg = e.message;
    }
    return exceptionMsg;
}

strictEqual(testParse(), undefined, 'ps data parses with no exceptions');

This will show me the exception message when it fails.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top