8 min read
How to prove your refactor changed nothing
Instead of hoping a large refactor introduced no visual changes, I exhaustively generated every possible style the Button component could produce before and after the change, then compared the outputs.
You've seen this kind of pull request before. Four hundred lines have been moved around, the tests all pass, and the description just says "No visual change." The reviewer skims it, approves, and the team hopes that every conditional branch was copied over correctly.
I didn't want to rely on hope. When I extracted the styles from a design system's Button into separate helper functions, I captured every computed style the component could produce, both before and after. Then I diffed the two files. All 1,188 entries were identical.
Here's how, with a harness of about 30 lines. None of it is specific to theming or React.
The refactor
Static analysis had flagged the Button render function with a cognitive complexity of 48. Our limit was 15. The function was building styles inline for three variants, two sizes, three icon layouts, and four state flags (selected, disabled, loading, alert), pulling values from the active theme.
The solution was straightforward. I moved each block into its own helper: one for each variant, one for size, and one for icon layout. The estimated complexity dropped to 11.
But mechanical does not always mean safe. The style objects are built with conditional spreads, and in CSS-in-JS the order of those spreads determines which declaration wins. Move one spread in the wrong place and a disabled button might get the wrong color in a specific theme. The unit tests only cover a few cases. The visual tests only hit the stories that someone had written. Neither covers the full matrix.
An exhaustive golden master
This is a form of characterization testing, sometimes called golden-master testing. You record what the code currently does, without judging whether it's correct. After you change the code, you verify that the recording hasn't changed.
What makes this version different is that the recording is exhaustive. You enumerate every input value the code branches on, generate the cartesian product of those values, and run them all. If every combination produces the same output before and after, you know the refactor was a no-op across that entire space. The PR can report it as a fact rather than a hope.
Capturing the styles
Before the split there was no style function to call. The render function built the styles and passed them to a child element. So I wrote a throwaway Jest test using React Testing Library. It mocked the theme hook to supply each theme in turn and stubbed out the child element and icon so I could capture the style props they received.
Two things were important. First, I used styled-components' css() helper to flatten the styles. This gave me exactly what the styling engine would see: falsy values removed, nested arrays flattened, and declarations in the correct order. Second, I gave every entry a readable label like forest secondary small icon+text {"alert":true}. That way the diff would clearly show which combination had changed.
Where the 1,188 cases come from
It's the cartesian product of every theme, variant, prop combination (none, selected, disabled, loading, alert, and several pairs of those states), size, and icon layout. For each combination we record the button's style object. Icon layouts also record the icon's style, except during loading, when a spinner replaces the icon.
A generic harness
Most refactors don't even need mocks. If your logic is already a pure function, or can be wrapped as one (like getStyles(props, theme)), this is the whole harness. Just swap in your own function and input axes:
// dump.mjs. Usage: node dump.mjs <module> <out.txt>
import { writeFileSync } from 'node:fs';
import { pathToFileURL } from 'node:url';
const [modulePath, outFile] = process.argv.slice(2);
const { getStyles } = await import(pathToFileURL(modulePath).href);
// Every input the code branches on, and every value it can take. Themes are inputs too.
const themes = {
ocean: { brand: '#2563eb', text: '#222222', muted: '#999999' },
forest: { brand: '#15803d', text: '#1f2937', muted: '#8a8a8a' },
};
const axes = {
theme: Object.keys(themes),
variant: ['primary', 'secondary', 'tertiary'],
size: ['small', 'medium'],
selected: [false, true],
disabled: [false, true],
};
// Cartesian product of the axes: 2 × 3 × 2 × 2 × 2 = 48 cases.
const cases = Object.entries(axes).reduce(
(all, [axis, values]) => all.flatMap((c) => values.map((v) => ({ ...c, [axis]: v }))),
[{}],
);
// JSON.stringify keeps key order. The replacer shows `undefined` instead of dropping it.
const serialize = (v) => JSON.stringify(v, (_k, x) => (x === undefined ? '<undefined>' : x));
// One labeled case per line, so `diff` names the combination that moved.
const lines = cases.map(({ theme, ...props }) =>
`${theme} ${serialize(props)}\t${serialize(getStyles(props, themes[theme]))}`);
writeFileSync(outFile, lines.join('\n') + '\n');
console.log(`${lines.length} cases -> ${outFile}`);
A git worktree lets you run the old code without disturbing your working directory. You run the dump on the old version, then on the new one, and compare:
git worktree add /tmp/before HEAD # or the last commit before the refactor
node dump.mjs /tmp/before/src/styles.mjs before.txt
node dump.mjs src/styles.mjs after.txt
diff before.txt after.txt && echo identical
git worktree remove /tmp/before
If the module needs your build setup, you can symlink node_modules into the worktree. Even easier: capture the before file before you start refactoring.
I tested it on a stripped-down demo button with 48 cases. Pulling inline if statements into spread helpers produced an empty diff. But moving the disabled spread above the variant spread changed 24 lines: exactly the disabled cases, where the variant color was now overriding the muted color. It caught the exact class of bug we were worried about, in just a few seconds.
Why not use snapshot tests?
You could do this with snapshots. The idea is the same, just with a different output format:
// Vitest. One file for the whole matrix, readable as plain text.
// cases, serialize, getStyles and themes are the ones from dump.mjs.
test('Button styles: full matrix', async () => {
const lines = cases.map(({ theme, ...props }) =>
`${theme} ${serialize(props)}\t${serialize(getStyles(props, themes[theme]))}`);
await expect(lines.join('\n')).toMatchFileSnapshot('./__dumps__/button-styles.txt');
});
You run it on the old code, do your refactor, run it again. Any changed line fails the test. You have to do the initial snapshot run locally, because in CI Vitest will fail on a missing snapshot instead of creating it. Since toMatchFileSnapshot lets you choose the path, the "snapshot" is just a plain text file, the same one diff would show you.
The tool itself isn't that important. What matters is how the file is treated afterward. A snapshot test is meant to be kept around. A committed file with 1,188 style strings will break every time someone intentionally changes a style. After a few rounds, people stop reading the diff and just update the snapshot with -u. At that point it no longer proves anything, even though it still looks like it does.
Feel free to use snapshots as your throwaway harness if it fits your setup better. Just remember to delete both the file and the test before merging, the same way you would with the script.
What I learned
Serialize deterministically, and decide what "same" means. Preserve key order. A reordering counts as a change until shown otherwise, so don't sort keys just to make the diff pass. Understand what your serializer drops: JSON.stringify removes undefined values and functions and converts a Map to {}, which is why the harness replaces undefined with a sentinel. Functions and Maps will still disappear, so handle those cases explicitly if your code can return them. Even better, serialize using the same mechanism that consumes the output, like the css() helper did in the Button example.
Prove the harness can fail. A harness that captures nothing will always produce an empty diff. So I deliberately broke the code by swapping two keys in the size helper. That changed 756 of the 1,188 entries: every button style, but none of the icon styles, exactly as expected. I reverted the change, ran it again, and got an empty diff. Only then did the empty result actually mean something.
Cover every axis the refactored code reads. My first version of the harness only covered themes, variants, and prop sets because it was written for an earlier Button change. The split also moved size and icon code those cases never exercised, so I extended the axes first. Throw in deliberately incomplete theme objects too, with tokens missing. Fallback behavior is often where refactors go wrong.
Dumps reveal issues that tests miss. One run caught a style factory that was silently dropping keys a theme had always provided. No code in the codebase was reading those keys, so no test was failing. But consumers receive the full theme, not just the keys you happen to read.
Treat intentional diffs as a list to explain, not a count to approve. In a pure refactor, if anything differs, fix the refactor. When a change is supposed to affect the output, document it up front, for example "only disabled secondary buttons." Then verify that the diff touches exactly those lines and nothing else. A reviewer can validate this too. Even better, separate behavior changes from refactors into different commits.
Keep the harness temporary. I deleted mine before committing, for the same reason as the snapshot file. The harness is just evidence for this one pull request. The result belongs in the PR description.
What it doesn't prove
It proves that the style objects are identical for every input combination you enumerated. That's it.
It doesn't prove anything about pixels. The browser never rendered anything. It doesn't check DOM structure, because the Button harness stubbed out the child element. Any prop you forgot to include is a case you didn't test. This technique doesn't replace visual regression testing. It simply adds breadth: every combination, in seconds.
How to use this on your next refactor
- List every input the code branches on and every value each can take.
- Identify where the output leaves the code: a return value, a prop passed to a child, a request payload.
- Dump the cartesian product on the untouched code, one labeled case per line, with key order preserved.
- Refactor, dump again, and run
diff. An empty result means you're done. - Break the code on purpose once and confirm the diff catches it.
- Delete the harness. Add "N/N identical" plus the list of axes to your pull request description.
This works for any code with a large but enumerable input space: style factories, permission matrices, serializers, feature flag logic, URL builders, reducers.
"No visual change" is a claim reviewers have to accept on faith. "1,188 of 1,188 identical," with the axes listed beside it, is something they can actually verify.