5 Using dojo and dojo class loading in jasmine headless webkit
kidlingo edited this page 2011-07-26 07:42:26 -07:00

I love this gem - thanks for the great work. My project uses a mix of dojo and jQuery, and after tinkering with it a while, I got dojo class loading to work without a server. Here's how. The project has a WebContent directory in it containing all web content. The jasmine tests are run from the parent of that directory.

jasmine.yml:

src_files:
  - WebContent/js/test_bootstrap.js
  - WebContent/js/lib/dojo/dojo.js
  - WebContent/js/lib/jquery/jquery-1.4.4.js
  - WebContent/js/lib/mystuff/**/*.js
spec_files:
  - "WebContent/js/lib/mystuff/**/*[Ss]pec.js"

WebContent/js/test_bootstrap.js:

djConfig = {
    baseScriptUri: "file:///Users/me/projects/myproject/WebContent/js/lib/dojo",
    modulePaths: {'mystuff': 'file:///Users/me/projects/myproject/WebContent/js/lib/mystuff'}, 
    isDebug:false, 
    parseOnLoad: true
};

the command line:

jasmine-headless-webkit --jasmine-config ./jasmine.yml

The problems this solves:

Creating the global dojo object

Dojo classes call dojo.require and dojo,declare, so dojo needs to be a global variable by the time those files are loaded and parsed. Including dojo.js before the general glob pattern seems to ensure that dojo.js is loaded and run before anything after it. Likewise for jQuery.

Loading dojo classes using file URLs, i.e. not requiring a server

The second issue then is telling dojo where to find class files (modules), and getting it to load them using file URLs instead of http URLs, so if I have this in a js file:

dojo.require("mystuff.SomethingCool");

dojo knows where to look for mystuff/SomethingCool.js in the load path.

You do this by creating a global djConfig object before loading dojo.js, providing two key pieces of information. One is modulePaths, which is how you tell dojo where to find things. The other is baseScriptUri, which tells dojo where its home is.

Unlike djConfig.baseUrl, djConfig.baseScriptUri lets you specify the URL as a file URL, and dojo will load modules using file URLs instead of requiring a server.

To create this global djConfig object before dojo initializes itself, I include the test_bootstrap.js in the src_files list before dojo.js, which seems to ensure that test_bootstrap.js is run before dojo.js, thereby configuring dojo correctly when it loads.

Stop trying to load firebug.js

The third issue is getting dojo to stop trying to load firebug.js. You do this by setting isDebug to false.

And away you go. You can call dojo.require() in your specs and create instances of dojo classes for testing.