开发者

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 fri开发者_开发百科endly would be great.


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.


OK, here is my thoughts. You should write tests only for your own code, not third party code, so there is no need to test that RequireJS as a library is working correctly. (They have their own tests, which you should trust.)

So you should be able to assume, in your tests, that RequireJS is working. Just like you assume parseInt works, and setTimeout works, and Math.min works: the developers of those have their own tests, and you don't need to write more.

If it's not working (quite unlikely), or if you are using it incorrectly (marginally more likely), then your test should fail catastrophically: you will end up calling methods on objects that don't exist, for example.

With this in mind, you should unit test your individual RequireJS modules. To do this, either each test fixture should be enclosed in a module that requires its system-under-test module, or tests should be asynchronous, and as part of them they should require the system-under-test-module. Again, just assume you got the correct module back: if you didn't, i.e. if you are misusing RequireJS, the tests will fail catastrophically.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜