Assert
One of the Node modules is the assert. It is not a complete tool for unit testing but it is possible to use it without any additional to perform its tests.
Methods
fail
: Compares two values (style current and expected).
ok
: Check if the expression passed is true.
throws
, doesNotThrow
: The function passed should/should not launch an exception.
ifError
: Tests if past value is true; useful for testing error variable.
In addition to several methods Equal: Equal, notEqual, deepEqual, notDeepEqual, strictEqual, notStrictEqual.
Nodeunit
Based on the assert explained above, nodeunit is one of the simplest options to write your unit tests. It supports asynchronous tests.
Methods
The methods for testing are the same as the assert described above. In addition, for each test function the nodeunit sends you an object with the following functions:
expect(quantidade)
: Number of assertions that will be made in this test. If a number of different assertions from the past are made the test fails. Calling this function is optional.
done
: Ends the current test. This function must be called.
Writing the test module
To write a test module is very simple, just expose your test functions and receive in them a parameter with the object test nodeunit, for example:
exports.testaAlgo = function (test) {
test.expect(2);
test.ok(true, "este teste irá passar");
test.ok(false, "este teste irá falhar e essa mensagem será exibida");
test.done();
};
Running the tests
Just install nodeunit via npm:
npm install -g nodeunit
And then run the test:
nodeunit meuTeste.js
The exit is something like:
$ nodeunit meuTeste.js
✖ testaAlgo
Assertion Message: este teste irá falhar e essa mensagem será exibida
Configuring unit tests in the project
One of the ways to configure your tests in your project is to use the package json., example:
"scripts": {
"test": "nodeunit testes/*.js"
}
This way just run npm test
to run your tests.
Not to have to install nodeunit globally on your machine (paramêtro -g
of npm install
), you can use the local node of the *node_modules folder*:
"scripts": {
"test": "./node_modules/.bin/nodeunit testes/*.js"
}
I use Grunt-Jasmine, which uses Jasmine-Node.
– Daniel T. Sobrosa
Just to be boring: The correct is "unit test", not "unit test".
– Victor Stafusa