The asynchronous nature of the Node.js platform means accounting for asynchronous behavior in tests. Fortunately, the Node.js unit test frameworks help in dealing with this, but it's worth spending a few moments considering the underlying problem.
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 delete ${fname}`)); else callback(); }); } }); };
The nature of asynchronous code is such that its execution order is nonlinear, meaning that there is a complex relationship between time and the lines of code. Since this is the real world, and not science fiction, we don't have a time machine (blue box or not) to help us traverse the web of time, and therefore, we must...