Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RequireJS and Headless Test-Driven Development

I'm looking to use RequireJS for my next big JS project however I am having a hard time figuring out how to test for it in a headless testing environment. I'm new to both RequireJS and the test-driven approach to coding so anything that is noob friendly would be great.

like image 334
Spencer Carnage Avatar asked Jun 02 '11 01:06

Spencer Carnage


1 Answers

You can test RequireJS modules from the command line using r.js to run your scripts in Node.

Then, you can use Node modules, like assert, to create a test suite for yourself.

Here's an overly simple example:

scripts/simple.js:

define({ name: 'Really simple module' });

tests/test_simple.js:

require({ baseUrl: 'scripts' }, ['assert', 'simple'], function(assert, simple) {

    var test = function(callback) {
        var msg;
        try {
            callback();
        } catch (e) {
            msg = 'Failed: expected "' + e.expected + 
                  '" but got "' + e.actual + '" instead.';
        }
        if (!msg) {
            msg = 'Passed';
        }
        console.log(msg);
    };

    // This will pass
    test(function() {
        assert.equal(simple.name, 'Really simple module');
    });

    // This will fail
    test(function() {
        assert.equal(simple.name, 'Foo');
    });

});

Then, you could run the test from the top level directory of your project:

node path/to/r.js test/test_simple.js

And you could probably do better than that. The assert module is just the bare bones that you need for making yourself a test suite. If you don't want to roll your own, you might try using a package like CommonJS Test Runner, but be sure to read the r.js documentation first.

like image 50
thisgeek Avatar answered Oct 03 '22 07:10

thisgeek