In chapter 3, I introduced various stubbing techniques that I called “accepted,” in that they are usually considered safe for both the maintainability and readability of the code and the tests that they guide us to write. In this appendix, I’ll describe a few of the less accepted and less safe ways in which we can fake whole modules in our tests.
A.1 An obligatory warning
I have good news and bad news about global patching and stubbing out functions and modules. Yes, you can do it—I’ll show you several ways to accomplish this. Is it a great idea? I’m not convinced. The costs of maintaining your tests with the techniques I’ll show you tend to be, from my experience, worse than maintaining code that is well parameterized or has proper seams built in.
However, there might be special times when you need to use these techniques. Such times include, but are not limited to, faking dependencies in code that you do not own and cannot change, and sometimes when using immediately executable functions or modules. Another case is when a module exposes only functions without objects, which limits the faking options quite a bit.
Try to avoid using the techniques I describe in this appendix as much as you can. If you can find a way to write your tests or refactor your code so you don’t need these approaches, use that way. If all else fails, the techniques in this appendix are a necessary evil. If you must use them, try to minimize how much you use them. Your tests will suffer and will become more fragile and harder to read.
Let’s dive in.
A.2 Monkey-patching functions, globals, and possible issues
Monkey-patching refers to the act of changing the behavior of a running program instance at run time. I first encountered the term when I was working in Ruby, where monkey-patching is very common. In JavaScript, it’s just as easy to “patch” a function at run time.
In chapter 3 we looked at the issue of time management in our tests and code. With monkey-patching, we could look at any function, global or local, and replace it (for a specific JavaScript scope) with a different implementation. If we wanted to patch time, we could monkey-patch the global Date.now so that any code from that point on would be affected by this change, both production and test code.
Listing A.1 shows a test that does this for the original production code that uses Date.now directly. It fakes the global Date.now function to control time during the test.
Listing A.1 Issues in faking the global Date.now()
describe('v1 findRecentlyRebooted', () => {
test('given 1 of 2 machines under threshold, it is found', () => {
const originalNow = Date.now; ❶
const fromDate = new Date(2000,0,3); ❷
Date.now = () => fromDate.getTime(); ❷
const rebootTwoDaysEarly = new Date(2000,0,1);
const machines = [
{ lastBootTime: rebootTwoDaysEarly, name: 'ignored' },
{ lastBootTime: fromDate, name: 'found' }];
const result = findRecentlyRebooted(machines, 1, fromDate);
expect(result.length).toBe(1);
expect(result[0].name).toContain('found');
Date.now = originalNow; ❸
});
});
❶ Saving the original Date.now
❷ Replacing Date.now with a custom date
❸ Restoring the original Date.now
In this listing, we’re replacing the global Date.now with a custom date. Because this is a global function, other tests can be affected by it, so we clean up after ourselves at the end of the test by restoring the original Date.now to its rightful place.
There are several major issues in a test like this. First, these asserts throw exceptions when they fail, which means if they fail, the restoration of the original Date.now might never be executed, and other tests will suffer a “dirty” global time that might affect them.
It’s also cumbersome to save the time function and then put it back. It’s making its mark on the test and making it longer and harder to read, plus harder to write. It’s easy to forget to reset the global state.
Finally, we’ve impaired parallelism. Jest seems to handle this well, as it creates a separate set of dependencies for each test file, but with other frameworks that might run tests in parallel, there could be a race condition. Multiple tests can change or expect the global time to have a certain value. When running in parallel, these tests can collide and create race conditions in the global state and affect each other. It’s not required in our case, but if you wanted to eliminate uncertainty, Jest allows you to run the Jest command line with the extra --runInBand command-line parameter to avoid parallelism.
We can avoid some of these issues by resorting to the beforeEach() and afterEach() helper functions.
Listing A.2 Resorting to beforeEach() and afterEach()
describe('v2 findRecentlyRebooted', () => {
let originalNow;
beforeEach(() => originalNow = Date.now); ❶
afterEach(() => Date.now = originalNow); ❷
test('given 1 of 2 machines under threshold, it is found', () => {
const fromDate = new Date(2000,0,3);
Date.now = () => fromDate.getTime();
const rebootTwoDaysEarly = new Date(2000,0,1);
const machines = [
{ lastBootTime: rebootTwoDaysEarly, name: 'ignored' },
{ lastBootTime: fromDate, name: 'found' }];
const result = findRecentlyRebooted(machines, 1, fromDate);
expect(result.length).toBe(1);
expect(result[0].name).toContain('found');
});
});
❶ Saving the original Date.now
❷ Restoring the original Date.now
Listing A.2 solves some of our issues but not all of them. The good part is that we don’t need to remember to save and reset Date.now anymore, because beforeEach() and afterEach() will take care of it. It’s also now easier to read the tests.
But we still have a potential major issue with parallel tests. Jest is smart enough to run parallel tests only per file, which means the tests in this spec file will run linearly, but this behavior is not guaranteed for tests in other files. Any one of the parallel tests might have their own beforeEach() and afterEach() that reset global state and might affect our tests without realizing it.
I’m not a fan of faking global objects (i.e., “singletons” in most typed languages) when I can help it. There are always strings attached—extra coding, extra maintenance, extra test fragility, or affecting other tests indirectly and worrying about cleaning up all the time are some reasons why. Most of the time, the code comes out better when I factor seams into the design of the code under test instead of around it in an implicit manner, such as what we just did.
Especially when considering that more and more frameworks might start to copy Jest’s features and run tests in parallel, global fakes become more and more dangerous.
A.2.1 Monkey-patching a function the Jest way
To make the picture more complete, Jest also supports the idea of monkey-patching through the use of two functions that work in tandem: spyOn and mockImplementation . Here’s spyOn :
Date.now = jest.spyOn(Date, 'now')
spyOn takes as parameters the scope and the function that requires tracking. Note that we need to use a string as a parameter here, which is not really refactoring-friendly—it’s easy to miss if we rename that function.
A.2.2 Jest spies
The word “spy” has a slightly more interesting shade of grey to it than the terms we’ve encountered so far in this book, which is why I don’t like to use it too much (or at all) if I can help it. Unfortunately, this word is a major part of Jest’s API, so let’s make sure we understand it.
xUnit Test Patterns (Addison-Wesley, 2007), by Gerard Meszaros, says this in its discussion of spies: “Use a Test Double to capture the indirect output calls made to another component by the system under test (SUT) for later verification by the test.” The only difference between a spy and a fake or test double is that a spy is calling the real implementation of the function underneath, and it only tracks the inputs to and outputs from that function, which we can later verify through the test. Fakes and test doubles don’t use the real implementation of a function.
My refined definition of a spy is pretty close: The act of wrapping a unit of work with an invisible tracking layer on the entry points and exit points without changing the underlying functionality, for the purpose of tracking its inputs and outputs during testing.
A.2.3 spyOn with mockImplementation()
This “tracking without changing functionality” behavior that is inherent to spies also explains why just using spyOn won’t be enough for us to fake Date.now . It’s only meant for tracking, not faking.
To actually fake the Date.now function and turn it into a stub , we’ll use the confusingly named mockImplementation to replace the underlying unit of work’s functionality:
jest.spyOn(Date, 'now').mockImplementation(() => /*return stub time*/);
Too much “mock”
If I were in a position to decide on a new name for mockImplementation, I’d name it fakeImplementation , because it can easily be used to create either stubs that return data or mocks that verify the data being sent into them as parameters. The word “mock” is used far too often in our industry to signify anything that isn’t real, when the distinction could help us make less brittle tests. “Mock” in the name immediately implies that this is something we’ll verify against later on, at least when I look at it, and given how I treat the ideas of mocks versus stubs in this book.
Jest is littered with overuse of the word “mock,” especially when comparing its API to an isolation framework such as Sinon.js, which uses naming that is less surprising and avoids using “mock” where it’s not necessary.
Here’s how the spyOn and mockImplementation combo looks in our code.
Listing A.3 Using jest.SpyOn() to monkey-patch Date.now()
describe('v4 findRecentlyRebooted with jest spyOn', () => {
afterEach(() => jest.restoreAllMocks());
test('given 1 of 2 machines under threshold, it is found', () => {
const fromDate = new Date(2000,0,3);
Date.now = jest.spyOn(Date, 'now')
.mockImplementation(() => fromDate.getTime());
const rebootTwoDaysEarly = new Date(2000,0,1);
const machines = [
{ lastBootTime: rebootTwoDaysEarly, name: 'ignored' },
{ lastBootTime: fromDate, name: 'found' }];
You can see that the last piece of the puzzle in the code is inside afterEach() . We use another function called jest . restoreAllMocks , which is Jest’s way of resetting any global state that has been spied on to its original implementation with no extra fake layers around it.
Note that even though we are using a spy, we’re not verifying that the function was actually called. Doing that would mean we’re using it as a mock object, which we are not. We’re merely using it as a stub. With Jest, we have to go through a “spy” to stub stuff out.
All of the advantages and disadvantages I’ve listed before still apply here. I prefer using parameters when it makes sense, instead of using global functions or variables.
A.3 Ignoring a whole module with Jest is simple
Of all the techniques mentioned in this appendix, this is the safest because it does not deal with the internal workings of the unit under test. It just ignores things in a broad manner.
If we don’t care about the module at all during our tests, and we just want to get it out of the way of our scenario without getting any fake data back from it, a simple call to jest.mock('module path') at the top of the test file will do just fine, without too much fuss.
The next section helps if you want to simulate custom data in each test from a fake module, which makes us go through more hoops.
A.4 Faking module behavior in each test
Faking a module basically means faking a global object that gets loaded whenever import or require is used for the first time by the code under test. Depending on the test framework we’re using, the module might be cached internally or through the standard Node.js require.cache mechanism. Since this only happens once, when our test imports the system under test, we have a bit of an issue when we’re trying to fake different behavior or data for different tests in the same file.
To fake custom behavior for our fake module, we need to take care of the following in our tests: clean up the required module from memory, replace it, re-require it, and get the code under test to use the new module instead of the original one by requiring our code under test again. That’s quite a bit. I call this pattern Clear-Fake-Require-Act (CFRA):
-
Clear —Before each test, clear all the cached or required modules in the test runner’s memory.
-
During the arrange part of the test:
-
Fake —Fake the module that will be required by the
requireaction invoked by the test code. -
Require —Require the code under test just before invoking it.
-
-
Act —Invoke the entry point.
If we forget any of these steps, or perform them in the wrong order, or not at the right point in the test’s life cycle, there’ll be a lot of question marks when we execute the test and things seem not to be faking correctly. Worse, they might sometimes work correctly. Shudder.
Let’s look at a real example, starting with the following code.
Listing A.4 Code under test with a dependency
const { getAllMachines } = require('./my-data-module'); ❶
const daysFrom = (from, to) => {
const ms = from.getTime() - new Date(to).getTime();
const diff = (ms / 1000) / 60 / 60 / 24; // secs * min * hrs
console.log(diff);
return diff;
};
const findRecentlyRebooted = (maxDays, fromDate) => {
const machines = getAllMachines();
return machines.filter(machine => {
const daysDiff = daysFrom(fromDate, machine.lastBootTime);
console.log(`${daysDiff} vs ${maxDays}`);
return daysDiff < maxDays;
});
};
❶ The dependency to fake
The first line contains the dependency we need to break in our test. It’s the getAllMachines function, being destructured from my-data-module . Because we are using the function detached from its parent module, we can’t just fake functions on the parent module and expect our tests to pass. We have to get the destructured function to get a fake function during the destructuring process, and that’s where the tricky part comes in.
A.4.1 Stubbing a module with vanilla require.cache
Before we use Jest and other frameworks to fake a whole module, let’s see how we can achieve this effect and explore what’s going on in the various frameworks.
You can use the CFRA pattern without using any framework by using require.cache directly.
Listing A.5 Stubbing with require.cache
const assert = require('assert');
const { check } = require('./custom-test-framework');
const dataModulePath = require.resolve('../my-data-module');
const fakeDataFromModule = fakeData => {
delete require.cache[dataModulePath]; ❶
require.cache[dataModulePath] = { ❷
id: dataModulePath,
filename: dataModulePath,
loaded: true,
exports: {
getAllMachines: () => fakeData
}
};
require(dataModulePath);
};
const requireAndCall_findRecentlyRebooted = (maxDays, fromDate) => {
const { findRecentlyRebooted } = require('../machine-scanner4'); ❸
return findRecentlyRebooted(maxDays, fromDate); ❹
};
check('given 1 of 2 machines under the threshold, it is found', () => {
const rebootTwoDaysEarly = new Date(2000,0,1);
const fromDate = new Date(2000,0,3);
fakeDataFromModule([
{ lastBootTime: rebootTwoDaysEarly, name: 'ignored' },
{ lastBootTime: fromDate, name: 'found' }
]);
const result = requireAndCall_findRecentlyRebooted(1, fromDate);
assert(result.length === 1);
assert(result[0].name.includes('found'));
});
❶ Clear
❷ Fake
❸ Require
❹ Act
Unfortunately, this code will not work with Jest, because Jest ignores require.cache and implements its own caching algorithm internally. To execute this test, run it directly through the Node.js command line. You’ll see that I’ve implemented my own little check() function, so that I don’t use Jest’s API. This test will work just fine when using a framework such as Jasmine.
Remember this line in our code under test?
const { getAllMachines } = require('./my-data-module');
Our tests need to execute this destructuring every time we want to return a fake value. That means we’ll need to execute a require or import of the unit under test from our test code, not at the top of the file, but somewhere in the middle of our test execution. You can see where this happens in the following part of listing A.5:
const requireAndCall_findRecentlyRebooted = (maxDays, fromDate) => {
const { findRecentlyRebooted } = require('../machine-scanner4');
return findRecentlyRebooted(maxDays, fromDate);
};
It is because of this destructuring code pattern that modules are not just objects with properties, for which normal monkey-patching techniques can be used. We need to jump through more hoops.
Let’s map the four CFRA steps to the code in listing A.5:
-
Clear —This is part of the
fakeDataFromModulefunction, which is invoked during the test. -
Fake —we are telling
require.cache’s dictionary entry to return a custom object that seems to represent what a module looks like, but which has a custom implementation that returnsfakeData. -
Require —We are requiring the code under test as part of the
requireAndCall_ findRecentlyRebooted()function, which is invoked during the test. -
ACT —This is part of the same
requireAndCall_findRecentlyRebooted()function that is invoked by the test.
Notice that we do not use beforeEach() for this test. We are doing everything directly from the test, because each test will fake its own data from the module.
A.4.2 Stubbing custom module data with Jest is complicated
We’ve seen the “vanilla” way of stubbing custom module data. That’s not usually how you’d do it if you’re using Jest, though. Jest contains several confusingly and very closely named functions that deal with clearing and faking modules, including mock , doMock , genMockFromModule , resetAllMocks , clearAllMocks , restoreAllMocks , resetModules and more. Yay!
The code I’ll recommend here feels the cleanest and simplest of all of Jest’s APIs in terms of readability and maintainability. I do cover other variations on it in the GitHub repository at https://github.com/royosherove/aout3-samples and under the “other-variations” folder at http://mng.bz/Jddo .
This is the common pattern for faking a module with Jest:
-
Require the module you’d like to fake in your own tests.
-
Stub out the module above the tests with
jest.mock(modulename).
In each test, tell Jest to override the behavior of one of the functions in that module by using [modulename].function.mockImplementation() or mockImplementationOnce() .
The following is what it might look like.
Listing A.6 Stubbing a module with Jest
const dataModule = require('../my-data-module');
const { findRecentlyRebooted } = require('../machine-scanner4');
const fakeDataFromModule = (fakeData) =>
dataModule.getAllMachines.mockImplementation(() => fakeData);
jest.mock('../my-data-module');
describe('findRecentlyRebooted', () => {
beforeEach(jest.resetAllMocks); //<- the cleanest way
test('given no machines, returns empty results', () => {
fakeDataFromModule([]);
const someDate = new Date(2000,0,1);
const result = findRecentlyRebooted(0, someDate);
expect(result.length).toBe(0);
});
test('given 1 of 2 machines under threshold, it is found', () => {
const fromDate = new Date(2000,0,3);
const rebootTwoDaysEarly = new Date(2000,0,1);
fakeDataFromModule([
{ lastBootTime: rebootTwoDaysEarly, name: 'ignored' },
{ lastBootTime: fromDate, name: 'found' }
]);
const result = findRecentlyRebooted(1, fromDate);
expect(result.length).toBe(1);
expect(result[0].name).toContain('found');
});
Here’s how you can approach each part of CFRA with Jest.
The jest.mock and jest.resetAllMocks methods are all about faking the module and resetting the fake implementation to an empty one. Note that the module is still fake after resetAllMocks . Only its behavior is reset to the default fake implementation. Calling it without telling it what to return will yield weird errors.
With the FromModule method, we replace the default implementation with a function that returns our hardcoded values in each test.
We could have used mockImplementationOnce() to do mocking, instead of the fakeDataFromModule() method, but I find that this can create very brittle tests. With stubs, we normally shouldn’t care how many times they return the fake values. If we did care how many times they were called, we would use them as mock objects, and that’s the subject of chapter 4.
A.4.3 Avoid Jest’s manual mocks
Jest contains the idea of manual mocks , but don’t use them if you can help it. This technique requires you to put a special __mocks__ folder in your tests that contain hardcoded fake module code, with a naming convention based on the module’s name. This will work, but the maintainability costs are too high when you want to control the fake data. The readability costs are too high as well, as it increases scroll fatigue to an unneeded level, requiring us to switch between multiple files to understand a test. You can read more about manual mocks in the Jest documentation: https://jestjs.io/docs/en/manual-mocks.html .
A.4.4 Stubbing a module with Sinon.js
For comparison, and so that you can see that the pattern of CFRA repeats in other frameworks, here’s an implementation of the same test with Sinon.js—a framework dedicated to creating stubs.
Listing A.7 Stubbing a module with Sinon.js
const sinon = require('sinon');
let dataModule;
const fakeDataFromModule = fakeData => {
sinon.stub(dataModule, 'getAllMachines')
.returns(fakeData);
};
const resetAndRequireModules = () => {
jest.resetModules();
dataModule = require('../my-data-module');
};
const requireAndCall_findRecentlyRebooted = (maxDays, someDate) => {
const { findRecentlyRebooted } = require('../machine-scanner4');
return findRecentlyRebooted(maxDays, someDate);
};
describe('4 sinon sandbox findRecentlyRebooted', () => {
beforeEach(resetAndRequireModules);
test('given no machines, returns empty results', () => {
const someDate = new Date('01 01 2000');
fakeDataFromModule([]);
const result = requireAndCall_findRecentlyRebooted(2, someDate);
expect(result.length).toBe(0);
});
Let’s map the relevant parts with Sinon.
A.4.5 Stubbing a module with testdouble
Testdouble is another isolation framework that can easily be used to stub things out. Due to the refactoring already done in previous tests, the code changes are minimal.
Listing A.8 Stubbing a module with testdouble
let td;
const resetAndRequireModules = () => {
jest.resetModules();
td = require('testdouble');
require('testdouble-jest')(td, jest);
};
const fakeDataFromModule = fakeData => {
td.replace('../my-data-module', {
getAllMachines: () => fakeData
});
};
const requireAndCall_findRecentlyRebooted = (maxDays, fromDate) => {
const { findRecentlyRebooted } = require('../machine-scanner4');
return findRecentlyRebooted(maxDays, fromDate);
};
Here are the important parts with testdouble.
The test implementation is exactly the same as with the Sinon example. We’re also using testdouble-jest , as it connects to the Jest module replacement facility. This is not needed if we’re using a different test framework.
These techniques will work, but I recommend staying away from them unless there’s absolutely no other way. There is almost always another way, and you can see many of those in chapter 3.