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?
RequireJS loads each dependency as a script tag, using head. appendChild(). RequireJS waits for all dependencies to load, figures out the right order in which to call the functions that define the modules, then calls the module definition functions once the dependencies for those functions have been called.
RequireJS has been a hugely influential and important tool in the JavaScript world. It's still used in many solid, well-written projects today.
RequireJS is a JavaScript library and file loader which manages the dependencies between JavaScript files and in modular programming. It also helps to improve the speed and quality of the code.
2 Answers. Show activity on this post. require(["jquery"], function ($) { function doStuff(a, b) { //does some stuff } $('#the-button'). click(function() { doStuff(4, 2); }); });
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..
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With