Node.js has a useful built-in testing tool, the assert
module. Its functionality is similar to assert libraries in other languages. Namely, it's a collection of functions for testing conditions, and if the conditions indicate an error, the assert
function throws an exception.
At its simplest, a test suite is a series of assert
calls to validate the behavior of a thing being tested. For example, a test suite could instantiate the user authentication service, then make an API call, using assert
methods to validate the result, then make another API call, validating its results, and so on.
Consider a code snippet like this, which you could save in a file named deleteFile.js
:
const fs = require('fs'); exports.deleteFile = function(fname, callback) { fs.stat(fname, (err, stats) => { if (err) callback(new Error(`the file ${fname} does not exist`)); else { fs.unlink(fname, err2 => { if (err) callback(new Error(`could not...