Assert
One of the node modules is assert . It is not a complete tool for unit testing but you can use it without any additional tests.
Methods
-
fail
: Compares two values (current style and expected in>).
-
ok
: Checks if the passed expression is true.
-
throws
, doesNotThrow
: The past function should / should not throw an exception.
-
ifError
: Tests whether the passed value is true; useful for testing variable errors.
In addition to several equal methods: equal , notEqual , deepEqual , notDeepEqual , strictEqual , not html
Nodeunit
Based on the assert explained above, nodeunit is one of the simplest options to write your unit tests. Supports asynchronous testing.
Methods
The test methods are the same as the assert methods described above. In addition, for each test function nodeunit sends you an object with the following functions:
-
expect(quantidade)
: The 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 should 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 test object of the nodeunit, eg:
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 the nodeunit via npm:
npm install -g nodeunit
And then run the test:
nodeunit meuTeste.js
The output 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 way to configure your tests in your project is to use package.json , for example:
"scripts": {
"test": "nodeunit testes/*.js"
}
In this way you just run npm test
to run your tests.
To not have to install the nodeunit in a global way on your machine (parameter -g
of npm install
), you can use the local nodeunit of the * node_modules *:
"scripts": {
"test": "./node_modules/.bin/nodeunit testes/*.js"
}