Search code examples
testingrequirejsmocha.jsamdnode-assert

AssertionError: Missing expected exception when testing async requirejs call using mocha


I'm writing a test for my custom requirejs loader. On malformed input it it supposed to throw an error.

I'm using mocha and plain node-assert to test it like this:

it('throws a SyntaxError on malformed input', function(done){
    assert.throws(function(){ requirejs(['myLoader!malformedInput'], Function.prototype) }, SyntaxError);
    done();
});

The test fails due to:

AssertionError: Missing expected exception (SyntaxError)..

From what I understand reading the docs on assert my syntax should be ok. The error message is a little hard to understand too.

My best guess would be that this is due to the fact that the requirejs call is async, but then I don't know when to call done in this scenario?

Or am I misunderstanding something in the way that requirejs will handle the error that I pass to onload.error(e)?


Solution

  • assert.throws is not going to work for exceptions that are raised asynchronously. Here's an example of how it can be done using a RequireJS errback:

    var assert = require("assert");
    var requirejs = require("requirejs");
    
    requirejs.config({
        baseUrl: ".",
    });
    
    it('throws a SyntaxError on malformed input', function (done){
        requirejs(['fail'], function (fail) {
            // This should not be called.
            throw new Error("We were expecting a failure but none occurred!");
        }, function (err) {
            assert(err.originalError instanceof SyntaxError,
                    "We should get a SyntaxError.");
            done();
        });
    });
    

    The fail.js file should contain nonsensical code (i.e. that generates a SyntaxError). The second function passed to requirejs is an errback called when the load fails.