Testing with fakes: a clock and a file
Some code is hard to test for one reason only: it reaches for something outside itself. A function that reads Date.now() answers differently on every run, and one that opens a file needs that file to exist in the right place. The fix is not a testing library; it is a parameter.
This lesson takes the same rule twice: once for the clock and once for a file. The reader sees the version that reads the time itself, the version that takes the moment as an argument, the test that passes a fake clock in, and a store object that stands in for a file so the test needs no disk at all.
The function that reads the clock
The function below is the one that is hard to test. It asks the clock for the current moment and compares it with the moment the item was made, so its answer depends on when the test runs: a test can prove that something a day old has expired, but it cannot sit on the exact millisecond of the boundary without waiting for one.
The file hard.mjs:
const DAY = 24 * 60 * 60 * 1000;
function isExpired(createdAt) {
return Date.now() - createdAt > DAY;
}
console.log('one hour old is not expired:', isExpired(Date.now() - 60 * 60 * 1000));
console.log('two days old is expired:', isExpired(Date.now() - 2 * DAY));
node hard.mjs
one hour old is not expired: false
two days old is expired: true
The program prints two answers, but two answers are not a test: the two calls happen to sit far from the boundary, and nothing here checks the case that matters, which is a moment exactly one day old. The hidden input is the clock, and no assertion can set it.
Pass the value in
The same rule as a pure function: the moment becomes a parameter, and the function stops reading anything it cannot see. The two files below are the function on its own and a program that uses it, because the test in the next section imports the module and the program prints what it finds.
The file expiry.mjs:
export const DAY = 24 * 60 * 60 * 1000;
export function isExpired(createdAt, now) {
return now - createdAt > DAY;
}
The file clock.mjs:
import { DAY, isExpired } from './expiry.mjs';
const createdAt = 1000;
console.log('at the boundary it is not expired:', isExpired(createdAt, createdAt + DAY));
console.log('one millisecond later it is:', isExpired(createdAt, createdAt + DAY + 1));
console.log('a fake clock can sit anywhere:', isExpired(createdAt, 0));
node clock.mjs
at the boundary it is not expired: false
one millisecond later it is: true
a fake clock can sit anywhere: false
The three calls now name the moment, so the boundary is a number in the source and the answer is the same on every run. The function also became pure, which is what the lesson on pure functions asks for, and the caller decides where the real moment comes from.
The test with a fake clock
A fake is a value that takes the place of a dependency: here an object with the same method as the clock, or simply a number. The test file below imports the module and passes moments it chose, which is why it can check the boundary and the millisecond after it in the same run.
The file clock.test.mjs:
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { DAY, isExpired } from './expiry.mjs';
const createdAt = 1000;
test('a fresh item is not expired', () => {
assert.equal(isExpired(createdAt, createdAt + 1), false);
});
test('an item older than a day is expired', () => {
assert.equal(isExpired(createdAt, createdAt + DAY + 1), true);
});
test('the boundary belongs to the fresh side', () => {
assert.equal(isExpired(createdAt, createdAt + DAY), false);
});
node --test-reporter=dot clock.test.mjs
echo "exit code: $?"
...
exit code: 0
Three dots for three tests, and no clock anywhere in the file: the fake is the pair of numbers passed in. The runner is the one from the lesson before, and the dot reporter is used for the same reason, that the duration of a test is a different number on every run.
A fake instead of a file
A file is the other dependency that makes a test awkward, and it is replaced the same way: the function takes an object with a read method rather than a path, and the test passes a map. The text that comes back is JSON, which the function parses into an object, and the program below shows the two stores side by side, one that answers and one that refuses, which is all a test needs to know about a disk.
The file store.mjs:
export function readConfig(store) {
const text = store.read('config.json');
return JSON.parse(text);
}
const files = new Map([['config.json', '{"port":8080}']]);
const fakeStore = {
read: (name) => files.get(name),
};
const strictStore = {
read(name) {
throw new Error(`the real file ${name} is not here`);
},
};
console.log('the fake answers:', readConfig(fakeStore).port);
try {
readConfig(strictStore);
} catch (error) {
console.log('the other store threw:', error.message);
}
node store.mjs
the fake answers: 8080
the other store threw: the real file config.json is not here
The same function read both stores, because it asks for one method and nothing else. A test passes the fake and gets the same answers on a machine with no file at all, and the failure case is as easy as an object whose method throws. The next lesson is about the other half of a bug: the program that runs, prints and tells you nothing.
Exercises
- Add a code field to the fake store error and check it in a test.
- Write a test for a moment far in the past and one far in the future. Which of the two is expired?
- Change isExpired to take a clock object with a now method instead of a number. Which calls in the test file have to change?
- Make readConfig throw a ValidationError when the text has no port, and test it with a fake that returns {}.
- Write a fake whose read returns undefined. What does JSON.parse throw, and which message reaches the caller?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Why is a function that calls Date.now() hard to test?
Answer
Its answer depends on the moment the test runs
The input is hidden in the call, so a test cannot place the call on the boundary it wants.
-
What is a fake in this lesson?
Answer
A value passed in that stands for the real dependency
The fake is a clock, a store or a number the test controls, passed where the real thing would go.
-
What makes a dependency easy to replace in a test?
Answer
It arrives as a parameter or a field, not a global
A value the caller passes can be swapped, while a global can only be replaced by changing the module.
-
What does the store object hide from the function under test?
Answer
Where the text comes from
The function asks for a read method, so a map and a disk answer it the same way.
-
What does this program print?
function later(now, ms) { return now + ms; } const fakeClock = { now: () => 1000 }; console.log(later(fakeClock.now(), 500));Answer
1500
The fake answers 1000 and the function adds the 500 it was given.
-
What does this program print?
function isExpired(createdAt, now) { return now - createdAt > 100; } console.log(isExpired(0, 100), isExpired(0, 101));Answer
false true
A difference of exactly 100 is not greater than 100, and one more millisecond is.
-
What does this program print?
const text = "{\"port\":8080}"; const store = { read: () => text }; console.log(JSON.parse(store.read()).port);Answer
8080
The fake returns JSON text and the function parses it like a file.
-
What does a fake clock make possible?
Answer
A fixed moment, so the boundary can be tested
The test chooses the moment, so the exact boundary and the millisecond after it are both reachable.
-
What does this program print? ``
function stamp(clock) { returnat ${clock.now()}; } console.log(stamp({ now: () => 7 }));``Answer
at 7
The object has the method the function asks for, and the template writes its answer.
-
What is the difference between the two versions of isExpired?
Answer
One reads the clock itself and one is given the moment
The second has the moment as a parameter, which is what makes it pure and testable.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev