Node.js has a useful testing tool built-in with the assert
module. It's not any kind of testing framework but simply a tool that can be used to write test code by making assertions of things that must be true or false at a given location in the code.
The assert
module has several methods providing various ways to assert conditions that must be true (or false) if the code is properly functioning.
The following is an example of using assert
for testing, providing an implementation of test-deleteFile.js
:
const fs = require('fs'); const assert = require('assert'); const df = require('./deleteFile'); df.deleteFile("no-such-file", (err) => { assert.throws( function() { if (err) throw err; }, function(error) { if ((error instanceof Error) && /does not exist/.test(error)) { return true; } else return false; }, "unexpected error" ); });
If you are looking for a quick way to test, the assert
module can be useful when used this way. If it runs and no messages are printed, then the test passes.
$ node test-deleteFile.js
The assert module is used by many of the test frameworks as a core tool for writing test cases. What the test frameworks do is create a familiar test suite and test case structure to encapsulate your test code.
There are many styles of assertion libraries available in contributed modules. Later in this chapter, we'll use the Chai assertion library (http://chaijs.com/) which gives you a choice between three different assertion styles (should, expect, and assert).