To assert that the res object has not been modified, we need to perform a deep comparison of the res object before and after checkEmptyPayload has been called.
Instead of implementing this function ourselves, we can save time by using existing utility libraries. For instance, Lodash provides the cloneDeep method (lodash.com/docs/#cloneDeep) for deep cloning, and the isEqual method (lodash.com/docs/#isEqual) for deep object comparison.
To use these methods in our code, we can install the lodash package from npm, which contains hundreds of utility methods. However, we won't be using most of these methods in our project; if we install the entire utility library, most of the code would be unused. We should always try to be as lean as possible, minimizing the number, and size, of our project's dependencies.
Fortunately, Lodash provides a separate npm package for each method, so let's add them to our project:
$ yarn add lodash.isequal lodash.clonedeep --dev
For example, we can see from bundlephobia.com/result?p=lodash@4.17.10 that the lodash package is 24.1 KB in size after it's been minified and gzipped. Similarly, the lodash.isequal and lodash.clonedeep packages have a size of 3.7 KB and 3.3 KB, respectively. Therefore, by installing the more specific packages, we have reduced the amount of unused code in our project by 17.1 KB.
Now, let's use the deepClone method to clone the res object before passing it to checkEmptyPayload. Then, after checkEmptyPayload has been called, use deepEqual to compare the res object and its clone, and assert whether the res object has been modified or not.
Have a go at implementing it yourself, and compare your solution with ours, as follows:
import assert from 'assert';
import deepClone from 'lodash.clonedeep';
import deepEqual from 'lodash.isequal';
import checkEmptyPayload from '.';
describe('checkEmptyPayload', function () {
let req;
let res;
let next;
describe('When req.method is not one of POST, PATCH or PUT', function
() {
let clonedRes;
beforeEach(function () {
req = { method: 'GET' };
res = {};
next = spy();
clonedRes = deepClone(res);
checkEmptyPayload(req, res, next);
});
it('should not modify res', function () {
assert(deepEqual(res, clonedRes));
});
it('should call next() once', function () {
// Assert that `next` has been called
});
});
});
Next, we need a way to assert that the next function has been called once. We can do that by using test spies.