How to Implement Golden File Tests
Use golden files to test large output: compare against a stored artifact, review the diff on a change, and update the golden deliberately.
On this page
Introduction
Some output is too large or too structured to assert inline: a rendered HTML document, a generated source file, a formatted report, a serialized payload. Asserting it field by field is unreadable and incomplete, and the assertion drifts from the real output. A golden file is the output captured as one checked-in artifact, compared against on each run. The diff on a mismatch shows exactly what changed, which is both the failure and the review.
This tutorial covers capturing a golden, comparing and diffing, updating deliberately, and keeping the output stable. The examples use a golden-file helper, and the approach is the same as snapshot testing in Jest or approval testing in other frameworks.
Capture the output as a golden artifact
Run the code and store its output as a file next to the test, checked into the repository. The file is the expected output, in full, so a reader can see exactly what the code should produce without reconstructing it from assertions. For a generated file, the golden is that file; for an HTML render, the golden is the HTML; for a report, the golden is the report.
Name the golden for the test and the case it covers, so a table-driven suite has one golden per row. A single golden for a suite with several cases is ambiguous when it fails. The golden is a source artifact, reviewed and versioned like code, not a temporary file, because it is the specification of the output.
import { readFileSync, writeFileSync, existsSync } from 'node:fs';
function assertGolden(name, actual, { update = false } = {}) {
const path = 'test/golden/' + name + '.txt';
if (update || !existsSync(path)) {
writeFileSync(path, actual); // update mode rewrites the golden
return;
}
const expected = readFileSync(path, 'utf8');
if (actual !== expected) {
throw new Error('golden mismatch for ' + name + '\n' + diff(expected, actual));
}
}
Compare and show the diff
On a mismatch, print a diff between the golden and the actual output, so the failure shows what changed rather than dumping two large blobs. A line diff is the most useful: it marks the added, removed, and changed lines, which is what a reviewer needs. Without the diff, the failure says only that the output differs, and you must diff by hand.
Keep the comparison exact for stable output, and normalize where the output has an unavoidable variation. If a timestamp or a path legitimately varies, normalize it before the comparison, rather than weakening the test. The goal is that a diff represents a real change, not a run-to-run variation, so any variation must be removed from the output or normalized.
# on failure, the test prints a line diff
-<div class="total">100</div>
+<div class="total">101</div>
# the change is visible in one line, not in two large documents
Update the golden deliberately
Provide an update mode that rewrites the golden from the current output, but keep it separate from the test run and require the diff to be reviewed. On a legitimate change, run the update, then review the diff in the commit to confirm it is what you intended. On an unintended change, the diff shows the bug before it is committed.
A golden test that updates on every failure tests nothing, because it agrees with whatever the code produced. The value comes from the review of the diff, which is why the update is an explicit command and the diff is small and readable. Treat a golden change like a code change: it must be justified in the commit, not silently accepted.
Keep the output stable across runs
A golden comparison fails if the output varies between runs, so make the output deterministic. Remove timestamps, or fix the clock; sort collections so the order is stable; replace random values with a seeded generator; normalize absolute paths so a different machine produces the same output. Each variation that remains is a flake waiting to happen.
Where a value must vary, such as a generated id, replace it with a placeholder before the comparison, so the golden holds the placeholder and the comparison ignores the real value. Normalize the output in one function so the rule is in one place, and test that two runs of the same input produce the identical normalized output, which proves the determinism.
function normalize(output) {
return output
.replace(/\d{4}-\d{2}-\d{2}T[\d:.]+Z/g, '<TIMESTAMP>') // fixed clock placeholder
.replace(/id="[0-9a-f-]{36}"/g, 'id="<UUID>"') // volatile ids
.replace(/\/builds\/[^/]+/g, '<ROOT>'); // machine path
}
Test the mismatch and the update
Test that a changed output fails the comparison and the diff names the change, by feeding a different actual and asserting the error. Test that the update mode rewrites the golden and the next run passes. Test that two runs of the same input produce the same normalized output, which proves there is no hidden variation. These tests make the golden machinery itself trustworthy.
UPDATE_GOLDEN=1 npx vitest run # rewrite goldens
git diff test/golden/ # review the diff before committing
npx vitest run # the suite now passes on the new goldens
Common pitfalls
Updating the golden on every failure so it agrees with the code, no diff in the failure so the change is invisible, unstable output from a timestamp or an unsorted collection so the test flakes, one golden for several cases so a failure is ambiguous, and treating the golden as a temp file instead of a reviewed artifact are the recurring mistakes. A deliberate update with a reviewed diff, a diff on failure, a normalized output, one golden per case, and treating the golden as source address them.
Conclusion
A golden file is the whole expected output as one artifact, compared against each run. Capture the output as a reviewed golden, show a diff on a mismatch, update deliberately with a reviewed diff, and normalize the output so it is stable. Self-check by asserting a changed output fails with a named diff and that two runs produce the same normalized output. Then large output is tested precisely and its changes are reviewed in the commit.
Sources: Go: Golden files in tests, Jest: Snapshot testing, Approval tests (Wikipedia).
FAQ
- When is a golden file better than inline assertions?
- When the output is large or structured, such as rendered HTML, a generated file, a formatted report, or a serialized payload. An inline assertion for such output is unreadable and incomplete; a golden file is the whole expected output in one place, and its diff shows exactly what changed.
- How do I keep a golden test from being a rubber stamp?
- Require the diff to be reviewed in the commit, and make the update mode explicit and separate from the test run. A golden that is updated on every failure without review tests nothing, because it agrees with whatever the code produced.
Report a problem with this articleOpens a pre-filled issue on GitHub.