Nodeunit
Easy unit testing in node.js and the browser, based on the assert module.
Install / Use
/learn @caolan/NodeunitREADME
Nodeunit
Simple syntax, powerful tools. Nodeunit provides easy async unit testing for node.js and the browser.
DEPRECATED PROJECT
The project is very stale. We've kept it working on new versions of node, and sometimes merged small PRs that help teams relying on nodeunit.
Nodeunit was the arguably first testing framework developed for node. It was very useful at the time, but there's an overwhelming number of other worthwhile testing solutions out there that are actively maintained. tap, ava, tape, mocha, jasmine, jest, ... the list goes on and on.
If Nodeunit were truly bringing some different philosophy to the testing scene I'd say yes effort should be made to shore up it's development, but given how many other great options there are out there, a benefit of letting it atrophy is it's one less choice people have to make when choosing a testing solution. You are strongly encouraged to check out other more modern testing options.
Features
- Simple to use
- Just export the tests from a module
- Works with node.js and in the browser
- Helps you avoid common pitfalls when testing asynchronous code
- Easy to add test cases with setUp and tearDown functions if you wish
- Flexible reporters for custom output, built-in support for HTML and jUnit XML
- Allows the use of mocks and stubs
Contributors
- alexgorbatchev
- alexkwolfe
- azatoth
- kadirpekel
- lambdalisue
- luebken
- orlandov
- Sannis
- sstephenson
- thegreatape
- mmalecki
- and thanks to cjohansen for input and advice on implementing setUp and tearDown functions. See cjohansen's fork.
Also, check out gerad's nodeunit-dsl project, which implements a 'pretty dsl on top of nodeunit'.
More contributor information can be found in the CONTRIBUTORS.md file.
Usage
Here is an example unit test module:
exports.testSomething = function(test) {
test.expect(1);
test.ok(true, "this assertion should pass");
test.done();
};
exports.testSomethingElse = function(test) {
test.ok(false, "this assertion should fail");
test.done();
};
When run using the included test runner, this will output the following:
<img src="https://github.com/caolan/nodeunit/raw/master/img/example_fail.png" />Installation
There are two options for installing nodeunit:
-
Clone / download nodeunit from github, then:
make && sudo make install
-
Install via npm:
npm install nodeunit -g
API Documentation
Nodeunit uses the functions available in the node.js assert module:
- ok(value, [message]) - Tests if value is a true value.
- equal(actual, expected, [message]) - Tests shallow, coercive equality with the equal comparison operator ( == ).
- notEqual(actual, expected, [message]) - Tests shallow, coercive non-equality with the not equal comparison operator ( != ).
- deepEqual(actual, expected, [message]) - Tests for deep equality.
- notDeepEqual(actual, expected, [message]) - Tests for any deep inequality.
- strictEqual(actual, expected, [message]) - Tests strict equality, as determined by the strict equality operator ( === )
- notStrictEqual(actual, expected, [message]) - Tests strict non-equality, as determined by the strict not equal operator ( !== )
- throws(block, [error], [message]) - Expects block to throw an error.
- doesNotThrow(block, [error], [message]) - Expects block not to throw an error.
- ifError(value) - Tests if value is not a false value, throws if it is a true value. Useful when testing the first argument, error in callbacks.
Nodeunit also provides the following functions within tests:
- expect(amount) - Specify how many assertions are expected to run within a test. Very useful for ensuring that all your callbacks and assertions are run.
- done() - Finish the current test function, and move on to the next. ALL tests should call this!
Nodeunit aims to be simple and easy to learn. This is achieved through using existing structures (such as node.js modules) to maximum effect, and reducing the API where possible, to make it easier to digest.
Tests are simply exported from a module, but they are still run in the order they are defined.
Note: Users of old nodeunit versions may remember using ok, equals and
same in the style of qunit, instead of the assert functions above. These
functions still exist for backwards compatibility, and are simply aliases to
their assert module counterparts.
Asynchronous Testing
When testing asynchronous code, there are a number of sharp edges to watch out for. Thankfully, nodeunit is designed to help you avoid as many of these pitfalls as possible. For the most part, testing asynchronous code in nodeunit just works.
Tests run in series
While running tests in parallel seems like a good idea for speeding up your test suite, in practice I've found it means writing much more complicated tests. Because of node's module cache, running tests in parallel means mocking and stubbing is pretty much impossible. One of the nicest things about testing in javascript is the ease of doing stubs:
var _readFile = fs.readFile;
fs.readFile = function(path, callback) {
// it's a stub!
};
// test function that uses fs.readFile
// we're done
fs.readFile = _readFile;
You cannot do this when running tests in parallel. In order to keep testing as simple as possible, nodeunit avoids it. Thankfully, most unit-test suites run fast anyway.
Explicit ending of tests
When testing async code it's important that tests end at the correct point, not
just after a given number of assertions. Otherwise your tests can run short,
ending before all assertions have completed. It's important to detect too
many assertions as well as too few. Combining explicit ending of tests with
an expected number of assertions helps to avoid false test passes, so be sure
to use the test.expect() method at the start of your test functions, and
test.done() when finished.
Groups, setUp and tearDown
Nodeunit allows the nesting of test functions:
exports.test1 = function (test) {
...
}
exports.group = {
test2: function (test) {
...
},
test3: function (test) {
...
}
}
This would be run as:
test1
group - test2
group - test3
Using these groups, Nodeunit allows you to define a setUp function, which is
run before each test, and a tearDown function, which is run after each test
calls test.done():
module.exports = {
setUp: function (callback) {
this.foo = 'bar';
callback();
},
tearDown: function (callback) {
// clean up
callback();
},
test1: function (test) {
test.equals(this.foo, 'bar');
test.done();
}
};
In this way, it's possible to have multiple groups of tests in a module, each group with its own setUp and tearDown functions.
Running Tests
Nodeunit comes with a basic command-line test runner, which can be installed
using sudo make install. Example usage:
nodeunit testmodule1.js testfolder [...]
If no entry file specified, test defaults.
The default test reporter uses color output, because I think that's more fun :) I intend to add a no-color option in future. To give you a feeling of the fun you'll be having writing tests, lets fix the example at the start of the README:
<img src="https://github.com/caolan/nodeunit/raw/master/img/example_pass.png" />Ahhh, Doesn't that feel better?
When using the included test runner, it will exit using the failed number of assertions as the exit code. This means it exits with 0 when all tests pass.
Command-line Options
- --reporter FILE - you can set the test reporter to a custom module or on of the modules in nodeunit/lib/reporters, when omitted, the default test runner is used.
- --list-reporters - list available built-in reporters.
- --config FILE - load config options from a JSON file, allows the customisation of color schemes for the default test reporter etc. See bin/nodeunit.json for current available options.
- -t testName - run specific test only.
- -f fullTestName - run specific test only. fullTestName is built so: "outerGroup - .. - innerGroup - testName".
- --version or -v - report nodeunit version
- --help - show nodeunit help
Running tests in the browser
Nodeunit tests can also be run inside the browser. For example usage, see the examples/browser folder. The basic syntax is as follows:
test.html
<html>
<head>
<title>Example Test Suite</title>
<link rel="stylesheet" href="nodeunit.css" type="text/css" />
<script src="nodeunit.js"></script>
<script src="suite1.js"></script>
<script src="suite2.js"></script>
</head>
<body>
<h1 id="nodeunit-header">Example Test Suite</h1>
<script>
nodeunit.run({
'Suite One': suite1,
'Suite Two': suite2
});
