nickf
nickf

Reputation: 546443

Defining modules and using them immediately with RequireJS

I'm writing some tests for an application which is using RequireJS. Because of how the application works, it expects to get some classes via calling require. So, for testing, I have some dummy classes, but I don't want to have to put them into individual files just for this test. I'd much prefer to just define() them manually inside my test file like so:

define('test/foo', function () {
    return "foo";
});

define('test/bar', function () {
    return "bar";
});

test("...", function () {
    MyApp.load("test/foo"); // <-- internally, it calls require('test/foo')
});

The issue here is that the evaluation of those modules is delayed until a script onload event is fired.

From require.js around line 1600:

//Always save off evaluating the def call until the script onload handler.
//This allows multiple modules to be in a file without prematurely
//tracing dependencies, and allows for anonymous module support,
//where the module name is not known until the script onload event
//occurs. If no context, use the global queue, and get it processed
//in the onscript load callback.
(context ? context.defQueue : globalDefQueue).push([name, deps, callback]);

Is there some way I can manually trigger the queue to be evaluated?

Upvotes: 9

Views: 3233

Answers (2)

nickf
nickf

Reputation: 546443

The best I've found so far is to asynchronously require the modules:

define("test/foo", function () { ... });
define("test/bar", function () { ... });

require(["test/foo"], function () {
    var foo = require('test/foo'),
        bar = require('test/bar');
    // continue with the tests..
});

Upvotes: 1

keeganwatkins
keeganwatkins

Reputation: 3686

module definitions should be limited to one per file (see here). i would guess that having multiple modules defined in a single file breaks the internal loading mechanisms, which rely on the script's load event to determine that it is ready while resolving dependencies.

even if it's just for testing, i'd recommend splitting those definitions into multiple files.

hope that helps! cheers.

Upvotes: 0

Related Questions