Alex Rivera | Logout

Defining modules and using them immediately with RequireJS

Asked 2012-01-16T13:48:54.803
9

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?

Edit
Report

1 Answer

1

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..
});
answered 2012-01-16T18:20:08.447

Your Answer