3

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)?

m90
  • 11,434
  • 13
  • 62
  • 112

1 Answers1

8

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.

200jaky
  • 27
  • 5
Louis
  • 146,715
  • 28
  • 274
  • 320
  • That's exactly how I ended up solving this, thank you! – m90 Sep 29 '14 at 13:34
  • @Louis. Thanks though i'm not using RequireJS. Was wondering why testing schema was failing with the async/ await. saw this and was able to understand. This is how i'm doing with async/await. Please let me know if doing it correctly or not though the test is passing? `try { await user.save(); } catch(err) { assert.equal(err.errors.email.message, 'Invalid Email'); }` – Ankur Anand May 01 '17 at 14:17