Testing asynchronous code
The asynchronous nature of the Node platform means accounting for asynchronous behavior in the tests. Fortunately, the Node unit testing 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 should save in a file named deleteFile.js
:
var fs = require('fs'); exports.deleteFile = function(fname, callback) { fs.stat(fname, function(err, stats) { if (err) callback(new Error('the file '+fname+' does not exist')); else { fs.unlink(fname, function(err) { if (err) callback(new Error('Could not delete '+fname)); else callback(); }); } }); }
The nature of the asynchronous code is that the execution order is nonlinear, even though the code is written linearly, meaning there is a complex relationship between time and the lines of code. This snippet, like many written with...