Greg Babiars's Blog

Getting Testem, QUnit and RequireJS working together

As a big believer in the rapid feedback that continuous testing gives, I looked into a few of the options in the JavaScript space a few months ago. At the time, I liked Karma and decided to try it out with some side projects. It worked great with Ember and QUnit, so I decided to try getting it to work with our existing suite using RequireJS, QUnit and Backbone. After some time trying to get it working with the adapters, I decided to use Grunt to get something good enough up and moved on.

Fast forward to today and I was once again faced with the similar issue. I wanted to move a newer project to RequireJS so I went head to head with Karma once again. After a little more frustration, I decided to try Testem. It amazed me how little configuration was actually needed.

###Configuring Testem The first thing you’ll need to do is install testem globally using npm install -g testem. After that, you’ll need to create a testem.json file. For our case, we want to use the option to specify and actual html test file. We end up with our testem.json looking like:

{
    "test_page": "test.html",
    "src_files": [
        // pattern for files you want to watch
    ],
    "src_files_ignore": [
        // pattern for files you want to ignore
    ]
}

Our test.html file will look like:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link rel="stylesheet" href="components/qunit/qunit/qunit.css">
    <script src="components/qunit/qunit/qunit.js"></script>
    <script>
        QUnit.config.autostart = false;
    </script>
    <script src="/testem.js"></script>
    <script data-main="js/test/test-main" src="components/requirejs/require.js"></script>
</head>
<body>
    <div id="qunit"></div>
    <div id="qunit-fixture"></div>
</body>

One thing to note here is that we are turning off autostart for QUnit. This is needed to get our required files to load first.

###Configuring RequireJS Next, we need to create our test-main.js file we pointed to in the script tag above. What we’ll need is something like:

require.config({
    // put your path, shims, etc. here
});

require(['my.test'], function() {
    QUnit.start();
})

The main part of this is the second require block where I’m requiring and starting the tests. Right now we have our tests statically defined and we are up and running.

###Not there yet

Getting Testem running with QUnit and RequireJS turned out to be fairly simple, however, one thing we are missing is the autogenerated building of the test file that both Karma and Testem provide out of the box. I’ll have another post soon to discuss some solutions around that using Grunt.

Posted September 24, 2013

author Greg BabiarsWritten by Greg Babiars who builds things for the web. You can follow me on Twitter.