0
votes

I recently implemented a custom global error handler in my codebase, and I wanted to test its behavior in my QUnit+Sinon suite; however, this does not seem to work:

QUnit.test("It should fire an ajax request on errors", function(assert) {
    var done = assert.async();

    var myOnerror = window.onerror;
    window.onerror = function(msg, url, line, col, error) {
        myOnerror(msg, url, line, col, error);
        //Some assertions on myOnerror execution
        done();
    };

    banana(); //Trigger an error to have window.onerror execute
});

Since the ReferenceError caused by the banana() invocation is actually caught by QUnit itself, which stops the test execution with a failure.

Is there a way to tell QUnit that I want to handle errors on my own, or to manually throw errors so that my own window.onerror will be invoked instead of QUnit's?

1

1 Answers

1
votes

The problem, as you noticed, is that QUnit catches errors. You want this to happen so that your test run doesn't bomb if one of your tests does in fact throw an unexpected error. The trick here is that you do not want to test that errors get thrown. Instead, you want to test that there is in fact an onerror handler and that it works correctly.

To test that the error handler works correctly you do not have to throw an error! This might seem weird, but you don't. Instead, you can simply call your error handler function from within your test with fake arguments.

QUnit.test("It should fire an ajax request on errors", function(assert) {
    // Note that Error throwing is NOT async, so you shouldn't need this.
    // var done = assert.async();

    assert.strictEqual( window.onerror, myOnerror );

    myOnerror(
        "some test message",
        "src/js/ajax-stuff.js",
        13,
        29,
        new ReferenceError("some test message")
    );

    // write assertions here for what `MyOnerror` should have done.
});