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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With