Testing three.js with npm and mocha

Games, tools and graphics demos using three.js are sadly not exempt from bugs. In the Encounter project, my core maths and physics modules can sometimes break in non-obvious ways. We need automated testing!

This article shows how to get three.js into a node.js environment so that you can get medieval on your code. Tests can be run on the command line, or by automated CI tools like Travis.

Ask npm to create a new project file for you: $ npm init and accept all defaults by hitting Enter on all the prompts. This will create package.json.

Try and start the test feature with $ npm test. This will fail, which is expected. If you look in the package.json, the definition of the test script is "test": "echo \"Error: no test specified\" && exit 1"

Add mocha

Install mocha with $ npm install mocha --save-dev. Notice that node_modules/ is created and your dependencies appear in there. Also notice that your package.json has been updated: the property devDependencies is added and updated by the use of --save-dev.

When test is invoked, we just want to run mocha and specify a verbose reporter. By default this will run anything in test/. So let's edit package.json to use mocha for testing:

"test": "mocha --reporter list"

Rerun the test with $ npm test. This should now succeed, reporting 0 passing (1ms) or similar. A WINNER IS YOU.

Dealing with dependencies

If you're already using something clever like require.js or browserify, skip this part.

Typically a three.js project is going to run in the browser. Module loading is hence done by the browser executing a bunch of <script/> tags. Your individual files don't have to worry about dependencies.
In a nodejs context however, there is no index.html binding everything together, so you have to be explicit.

If you're exporting a module that depends on other files, you're going to have to tell node to load them. I use this approach:

At the start of your module, check to see if you're in a nodejs environment.

If so, explicitly declare your dependencies.

If not, you're probably in a browser so you don't need to do anything else.