Running test suites recursively with nodeunit

Perry Mitchell / 2016-08-31 17:20:09
Running test suites recursively with nodeunit

Nodeunit is a pow­er­ful yet sim­ple test run­ner built with NodeJS. It’s the test run­ner of choice for my node pro­jects and takes al­most no time at all to setup a good suite of tests. Suites are just JavaScript files, so they can in­clude any part of your ap­pli­ca­tion or its de­pen­den­cies when writ­ing tests, so in­te­gra­tion with NodeJS ap­pli­ca­tions is a breeze.

Basic setup

Once you’ve in­stalled node­u­nit from npm, we can write a ba­sic spec to see how it works. Let’s as­sume you have a spec file called example.js in­side a test di­rec­tory in your pro­ject that con­tains the fol­low­ing:

module.exports = {
    exampleTest: function(test) {
        test.ok(true, "Should be true");
        test.done();
    }
};

Running ./node_modules/nodeunit/bin/nodeunit (you can use just nodeunit in your package.json scripts) from within your pro­ject di­rec­tory should show some­thing like the fol­low­ing:

example
✔ exampleTest

OK: 1 assertions (12ms)

You could have also spec­i­fied the tests di­rec­tory via ./node_modules/nodeunit/bin/nodeunit test, or the ex­act file with ./node_modules/nodeunit/bin/nodeunit test/example.js.

Recusive op­er­a­tion

Let’s as­sume we have a sub di­rec­tory in our test folder called sub, and this di­rec­tory has a test suite called example2.js:

module.exports = {
    exampleSubTest: function(test) {
        test.ok(true, "Should also be true");
        test.done();
    }
};

Running the name node­u­nit com­mand will show the sam­ple re­sult as be­fore:

example
✔ exampleTest

OK: 1 assertions (11ms)

This is be­cause node­u­nit does not re­cu­sively search di­rec­to­ries. I re­cently added a PR to the node­u­nit repo for re­cur­sive­ness sup­port via a flag (-r). Running ./node_modules/nodeunit/bin/nodeunit -r should now show the nested suite re­sults:

example
✔ exampleTest

example2
✔ exampleSubTest

OK: 2 assertions (14ms)

The fea­ture has only just been merged into master, so it should take some time be­fore be­ing re­leased to npm.