node-test
is a simple, asynchronous test runner. It's designed to address what are limitations of existing Node.js test runners. Writing tests should be just like writing any other code.
- Core Philosophy
- Comparison With Other Test Runners
- Install
- Example
- API
- Running Multiple Suites
- Custom Reporters
- Todo
- Fast - Concurrent Tests
- No global variables
- Optional CLI - Running a test file directly (
node test/test-something.js
) produces the same output as using the CLI. - Minimal - Just runs your tests and gives you the results. There's no fancy error interpretation, just a plain old Node.js error callstack.
- No planning tests or counting assertions.
- Asynchronous Tests - Prefers Promises, but supports Callbacks
- Built-In assertion library build on the core
assert
module
These test runners have many great features and heavily inspired this module. However, there are key differences.
- Tests are run serially (one at a time).
- Defaults to using global variables (
describe()
,it()
, etc). - Mocha CLI is required, directly running a mocha test files fails.
- Tests are run serially (one at a time).
- The number of assertions has to be manually counted and planned (
t.plan()
) for every test.
- Ava CLI is required, so directly running a test files fails.
- Ava's stack trace interpreter often removes helpful information, accesses properties on your object (causing side effects), and can interfere with other libraries built in error reporting (ie. Long Stack Traces)
$ npm install --save-dev node-test
'use strict';
const Suite = require('node-test');
const suite = new Suite('My Suite Name');
suite.test('Test 1', t => {
return funcReturnsPromise()
.then(result => {
t.equal(result, 2);
});
});
suite.skip('Test 2', t => {
throw new Error('skipped');
});
suite.todo('Test 3 - Coming Soon');
suite.test('Test 4', (t, state, done) => {
funcWithCallback(done);
});
suite.failing('Test 5 - Need to fix this', t => {
t.equal(1+1, 3);
});
Output:
----My Suite Name----
pass 1 - Test 1
skip 2 - Test 2
todo 3 - Test 3 - Coming Soon
pass 4 - Test 4
fail 5 - Test 5 - Need to fix this #failing test
Total: 3
Failed: 1 (5)
Passed: 2 67%
Process finished with exit code 0
The first thing you do with node-test
is create a suite for your tests.
name
: string - title for testoptions
: objectfailFast
: boolean (default: false) - if a single test fails, stop all remaining tests in the suite
const Suite = require('node-test');
const suite = new Suite('My Suite Name');
By default node-test
runs tests concurrently. Concurrency means that the tests must be atomic. They should not depend on other tests for state.
The following methods are used to create concurrent tests.
name
: string - title for testaction
: function(t, state, done) - test implementationt
: object (built-in assertions)- (optional)
state
: object - result ofbeforeEach
hook - (optional)
done
: function - callback for asynchronous tests validateError
: function - function to validate the error
- Any
Error
throw synchronously will cause the test to fail. - Asynchronous test can return a Promise or use the
done()
callback.- If the test returns a Promise, the test will pass or fail if the promise resolves or rejects, respectively.
- If the
done()
callback is used, the test will fail if the first argument is defined. See Node.js style callbacks.
validateError
can turn a failing test into a passing test, if the error validates. (see below)
suite.test('My Test', t => {
const result = funcReturnsNumber();
t.equal(result, 2);
});
suite.test('My Test', t => {
return funcReturnsPromise()
.then(result => {
t.equal(result, 2);
});
});
suite.test('My Test', (t, state, done) => {
funcWithCallback((err, result) => {
t.noError(err);
t.equal(result, 2);
});
});
suite.test('My Test 2', (t, state, done) => {
funcWithCallbackNoValue(done);
});
validateError
tests that a specific error was throw. This is makes it easy to test to test error conditions. The test will pass, if validateError
is passed and does not throw.
t.throws(() => {
return Promise.reject(new Error('expected error'));
},
err => {
t.true(err instanceof Error);
t.equal(err.message, 'expected error');
});
t.throws(() => {
return Promise.reject(new Error('expected error'));
},
err => {
t.equal(err.message, 'other error');
});
Same as suite.test()
.
When the suite run, only
tests will be run and all other tests will be skipped.
Same as suite.test()
.
The "test" will be shown in the output, but will not count toward the total.
name
: string - title for test
The test included as a failed test in the output, but don't cause the exit code to change (indicating the build failed).
Same as suite.test()
.
node-test
also supports serial tests (one at a time). Most of the time concurrent test are preferable, however there are times (such as when accessing a database) that you may want tests to run serially.
Within a suite, serial tests are executed first followed by any concurrent tests. However, multiple suites are run concurrently. So two serial tests could run at the same time if they are members of different suites.
The following methods are used to create serial tests. There usage is identical to the equivalent concurrent method.
Same as suite.test()
.
Same as suite.test()
.
Same as suite.test()
.
Same as suite.test()
.
Same as suite.test()
.
node-test
provides four hooks. The hooks are run serially to the tests.
name
: string - title for testaction
: function(t, state, done) - test implementationt
: object (built-in assertions)- (optional)
done
: function - callback for asynchronous tests
Same as suite.before()
.
Same as suite.before()
.
The beforeEach
hook runs before each test in the suite.
suite.beforeEach(t => {
return {
data: 2
};
});
suite.test('My Test 1', (t, state) => {
t.equal(1+1, state.data);
state.date = 3;
});
suite.test('My Test 2', (t, state) => {
t.equal(2, state.data); //state is still 2, because beforeEach is run individual for each test
});
Same as suite.before()
.
Tests whose execution time exceeds the delay will fail.
delay
: number - timeout in milliseconds
node-test
includes an assertion library that is a bit more feature rich than the core assert module.
- For every method,
message
is optional. If defined, it will be displayed if the assertion fails.*
t.pass();
t.fail();
An assertion that value
is strictly true.
const value = true;
t.true(value);
const arr = ['a'];
t.true(arr.length === 1);
An assertion that value
is strictly false.
const value = false;
t.false(value);
An assertion that value
is strictly truthy.
const value = 1;
t.truthy(value);
An assertion that value
is strictly falsey.
const value = 0;
t.falsey(value);
An assertion that value
is strictly equal to expected
.
const value = 1;
t.equal(value, 1);
An assertion that value
is strictly not equal to expected
.
const value = 1;
t.notEqual(value, 2);
An assertion that value
is strictly and deeply equal to expected
. Deep equality is tested by the not-so-shallow module.
const value = { data: 1234 };
t.deepEqual(value, { data: 1234 });
An assertion that value
is strictly and deeply not equal to expected
.
const value = { data: 1234 };
t.notDeepEqual(value, { data: 5678 });
An assertion that value
is greater than expected
.
const value = 2;
t.greaterThan(value, 1);
An assertion that value
is greater than or equal to expected
.
const value = 2;
t.greaterThanOrEqual(value, 2);
An assertion that value
is less than expected
.
const value = 1;
t.lessThan(value, 2);
An assertion that value
is less than or equal to expected
. *message
is optional. If defined, it will be displayed if the assertion fails.
const value = 1;
t.lessThanOrEqual(value, 1);
An assertion that error
is falsey. This is functionally similar to t.falsey()
, but the assertion error message indicates the failure was due to an Error
.
funcWithCallback((err, result) => {
t.noError(err);
});
An assertion that fn
is function that does not throws an Error synchronously nor asynchronously (via Promise or callback).
fn
: function([done]) - code to assert throws- (optional)
done
: function - callback for asynchronous test
- (optional)
Would Pass:
t.notThrows(() => {
t.equal(1, 1);
});
Would Fail:
t.throws(() => {
throw new Error('error');
});
t.notThrows(() => {
return funcReturnsPromise();
});
The callback can be asynchronous or synchronous. The callback can be executed immediately or later. It will be handled the same.
t.notThrows(done1 => {
funcWithAsyncCallback(done1);
});
t.notThrows(done1 => {
funcWithSyncCallback(done1);
});
t.notThrows(done1 => {
funcWithCallback((err, result) => {
t.noError(err);
t.equal(result, 2);
done1();
});
});
Even if an asynchronous mode is used, synchronous errors are caught.
Would Fail:
t.notThrows(done => {
funcWithAsyncCallback(done);
throw new Error('message');
});
t.notThrows(done => {
throw new Error('message');
return funcReturnsPromise();
});
An assertion that fn
is function that either throws an Error synchronously or asynchronously (via Promise or callback).
fn
: function([done]) - code to assert throws- (optional)
done
: function - callback for asynchronous test validateError
: function - function to validate the error
- (optional)
Except for the validateError
argument, this functions as the opposite of t.notThrow()
. That is throws
passes when there is an Error rather passing when there is no Error. For more usage details, look at the notThrows
examples.
Passing errTestFn
allows testing that the Error received is the Error expected.
t.throws(() => {
return funcReturnsPromise();
},
err => {
t.true(err instanceof TypeError);
t.equal(err.message, 'invalid argument');
});
An asynchronous assertion that fn
eventually executes a callback a precise number of times.
t.count(done1 => {
funcWithCallback(done1);
funcWithCallback(done1);
funcWithCallback(done1);
}, 3);
There are couple ways to run multiple suites.
-
The easiest (and least flexible) way to just place multiple suites in a single file.
-
A more flexible way is to create one suite per file and create an index file to run them all.
Imagine your
test
directory looks like this:suite1.js suite2.js suite3.js
You could create a file called
index.js
with these contents:'use strict'; require('./suite1'); require('./suite2'); require('./suite3');
Then add the script to your
package.json
file:"scripts": { "test": "node test/index.js" }
Now you can run individual suites or the whole thing from the command line.
node tests/suite1.js npm test
-
The up coming CLI will make it easier to execute multiple suites without needing to maintain an
index.js
.
A reporter is a simple constructor function that takes an event emitter as it's only argument. The emitter emit four different events.
function Reporter(emitter) {
emitter.on('start', root => {
console.log('testing started');
});
emitter.on('testEnd', test => {
});
emitter.on('suiteEnd', suite => {
});
emitter.on('end', () => {
});
}
Emitted before tests start running.
root
: objectsuites
: array - suites that will be run (seesuiteEnd
for suite structure)
Emitted after a test has completed.
test
: objectname
: string - name of testsuite
: object - suite the test belongs tostatus
: string -pass
,fail
,todo
,skip
, orstop
runTime
: number - run time of test in milliseconds
Emitted after a suite has completed.
suite
: objectname
: string - name of testerr
: Error|undefined - suite level errors, such as beforeAll and afterAll hook errorstests
: array - all tests in the suite (seetestEnd
for test structure)
Emitted when all suites are completed.
- CLI
- file watcher
- only run certain files (glob matching)
- harmony flag
- code coverage
- slow tests
- logging - ala Karma
- support CoffeeScript, TypeScript
- support plugins