Finding Display Changes in React with Vitest Snapshots
Vitest's snapshot testing can catch unintended changes to the text or class names of a React component. It saves the rendered result to a file. If the next run differs from the saved record, the test fails and shows the difference. This is useful after a refactoring or a library update, when you want to confirm that the display (the DOM) has not changed.
In my test environment, I rendered a small component that shows a price with React Testing Library. I then checked recording, diffs, updating, and behavior in CI, in that order.
The test environment was Ubuntu 24.04 with Node.js 22.23.4. I used vitest 5.1.0, jsdom 31.0.0, @testing-library/react 16.3.3, @testing-library/dom 10.4.2, react / react-dom 19.3.1, @vitejs/plugin-react 6.3.0, and typescript 7.0.2. I did not try the operation of pressing the u key in watch mode to update, toMatchFileSnapshot(), or image comparison in browser mode (toMatchScreenshot()).
- 1. Recording the rendered result in a snapshot
- 2. When the display changes, the test fails with a diff
- 3. If the change is intended, update the record with -u
- 4. In CI, the test fails even when a record is just missing
- 5. When you delete a test, remove its unused records too
- 6. Recording only the part you want to watch with an inline snapshot
- 7. When useId values cause failures, replace them with a serializer
Recording the rendered result in a snapshot
The component I tried shows a product name and its price, and it also shows a badge when the item is on sale.
// src/PriceTag.tsx
type Props = {
name: string;
price: number;
onSale?: boolean;
};
export function PriceTag({ name, price, onSale = false }: Props) {
return (
<div className={onSale ? 'price-tag price-tag--sale' : 'price-tag'}>
<span className="price-tag__name">{name}</span>
<span className="price-tag__price">{price.toLocaleString('ja-JP')}円</span>
{onSale && <span className="price-tag__badge">セール中</span>}
</div>
);
}
In the test, I take the rendered DOM from asFragment(), which render() from React Testing Library returns, and pass it to Vitest's toMatchSnapshot().
// src/PriceTag.test.tsx
import { render } from '@testing-library/react';
import { expect, test } from 'vitest';
import { PriceTag } from './PriceTag';
test('通常の価格の表示', () => {
const { asFragment } = render(<PriceTag name="猫用ブラシ" price={1980} />);
expect(asFragment()).toMatchSnapshot();
});
test('セール中の表示', () => {
const { asFragment } = render(<PriceTag name="猫用ブラシ" price={1480} onSale />);
expect(asFragment()).toMatchSnapshot();
});
For the Vitest configuration, I only added the React plugin and set the test environment to jsdom.
// vitest.config.ts
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
},
});
On the first run, the tests passed and the output showed that two snapshots were written. I replaced the project path in the output with <project>.
$ npx vitest run
RUN v5.1.0 <project>
Snapshots 2 written
Test Files 1 passed (1)
Tests 2 passed (2)
The snapshots were written to __snapshots__/PriceTag.test.tsx.snap, next to the test file. Each test name had its DOM saved as a formatted string. The excerpt below shows only the on-sale display entry.
exports[`セール中の表示 1`] = `
<DocumentFragment>
<div
class="price-tag price-tag--sale"
>
<span
class="price-tag__name"
>
猫用ブラシ
</span>
<span
class="price-tag__price"
>
1,480円
</span>
<span
class="price-tag__badge"
>
セール中
</span>
</div>
</DocumentFragment>
`;
The Vitest snapshot guide recommends committing this file along with the code and checking it in code review. Without the record in the repository, there is nothing to compare against in the next run.
When the display changes, the test fails with a diff
I changed the badge in the component to <span className="badge">SALE</span> and ran npx vitest run again. The on-sale display test failed, and the changed lines were shown with - (the record) and + (the current render). The output below shows only the diff part.
FAIL src/PriceTag.test.tsx > セール中の表示
Error: Snapshot `セール中の表示 1` mismatched
- Expected
+ Received
@@ -11,11 +11,11 @@
class="price-tag__price"
>
1,480円
</span>
<span
- class="price-tag__badge"
+ class="badge"
>
- セール中
+ SALE
</span>
</div>
</DocumentFragment>
The regular price display test, which shows no badge, passed as before. The exit code was 1, and the snapshot file was not rewritten. When a test fails, read this diff and decide whether the change was intended or whether it was made by accident.
If the change is intended, update the record with -u
If the diff matches what you intended, run with -u (--update). The record is then replaced with the current render.
$ npx vitest run -u
RUN v5.1.0 <project>
Snapshots 1 updated
Test Files 1 passed (1)
Tests 2 passed (2)
After the update, the .snap file contains class="badge" and SALE, and a run without -u passes. According to the guide, in watch mode you can also update failing snapshots by pressing the u key in the terminal.
According to the official configuration documentation, -u overwrites every changed snapshot with the current render and also deletes records that are no longer used. If you add -u without reading the diff, a real display breakage can be saved as the "correct" record. After updating, also check the changes to the .snap file before you commit.
In CI, the test fails even when a record is just missing
Vitest does not write snapshots when the environment variable CI is set. According to the update configuration documentation, when nothing is specified, it writes only new snapshots locally. In CI, it writes nothing and fails on any mismatch, any missing snapshot record, or any obsolete snapshot.
To check this, I added a new test for a price of 0 yen. Then I ran it with CI=true while the .snap file had no record for it. The output below omits some lines.
$ CI=true npx vitest run
FAIL src/PriceTag.test.tsx > 0円の表示
Error: Snapshot `0円の表示 1` mismatched
❯ src/PriceTag.test.tsx:17:24
Snapshots 1 failed
Test Files 1 failed (1)
Tests 1 failed | 2 passed (3)
The error is the same mismatched error as when the display changed, but no diff is shown. The zero-yen test entry was also not written to the .snap file. When I ran without CI, the output said "1 written" and the record was saved. So when you add a new test, run it locally once and include the .snap file in your commit.
When you delete a test, remove its unused records too
Next, I deleted the zero-yen test I had added and ran the tests. With npx vitest run, the tests passed, and the only thing shown was a note that an obsolete snapshot existed. The output below shows the final summary.
Snapshots 1 obsolete
↳ src/PriceTag.test.tsx
· 0円の表示 1
Test Files 1 passed (1)
Tests 2 passed (2)
With CI=true in the same state, all the tests passed, but the test file was marked as failed and the exit code was 1. The output below shows only the error part.
FAIL src/PriceTag.test.tsx [ src/PriceTag.test.tsx ]
Error: Obsolete snapshots found when no snapshot update is expected.
· 0円の表示 1
When I ran with -u, the output showed "1 removed", and the zero-yen record was deleted from the .snap file. When you rename a test, the record under the old name remains in the same way (this is described in the CI section of the guide).
Recording only the part you want to watch with an inline snapshot
If you record the whole component, a change to an unrelated part also fails the test. If you only want to watch how the price is written, you can pass just that part to toMatchInlineSnapshot(). If you call it with no arguments and run the tests, Vitest writes the record into the test file itself.
// src/PriceTagInline.test.tsx (before running)
import { render, screen } from '@testing-library/react';
import { expect, test } from 'vitest';
import { PriceTag } from './PriceTag';
test('セール中の価格とバッジ', () => {
const { container } = render(<PriceTag name="猫用ブラシ" price={1480} onSale />);
expect(container.querySelector('.price-tag__price')?.textContent).toMatchInlineSnapshot();
expect(screen.getByText('SALE')).toMatchInlineSnapshot();
});
After running, the test file was rewritten as follows.
// src/PriceTagInline.test.tsx (after running. The three import lines are the same, so they are omitted)
test('セール中の価格とバッジ', () => {
const { container } = render(<PriceTag name="猫用ブラシ" price={1480} onSale />);
expect(container.querySelector('.price-tag__price')?.textContent).toMatchInlineSnapshot(`"1,480円"`);
expect(screen.getByText('SALE')).toMatchInlineSnapshot(`
<span
class="badge"
>
SALE
</span>
`);
});
When I changed the component's price formatting to toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' }), the first record failed. The output below shows only the error part.
Error: Snapshot `セール中の価格とバッジ 1` mismatched
Expected: ""1,480円""
Received: ""¥1,480""
The expected value is visible inside the test, so you can tell what the test checks without opening another file.
When useId values cause failures, replace them with a serializer
When I recorded a component that uses useId() to link a label and an input, the .snap file contained values like for="_r_0_" and id="_r_0_".
// src/Field.tsx
import { useId } from 'react';
export function EmailField() {
const id = useId();
return (
<p>
<label htmlFor={id}>メールアドレス</label>
<input id={id} type="email" />
</p>
);
}
The problem is that this value changes depending on the order of the tests. I added another test to the same test file, placed before this one, that only renders EmailField. Even though the display did not change, the snapshot failed. The output below shows only the diff part.
FAIL src/Field.test.tsx > メールアドレスの欄
Error: Snapshot `メールアドレスの欄 1` mismatched
- Expected
+ Received
<DocumentFragment>
<p>
<label
- for="_r_0_"
+ for="_r_1_"
>
メールアドレス
</label>
<input
- id="_r_0_"
+ id="_r_1_"
type="email"
/>
</p>
</DocumentFragment>
You can remove this kind of difference, which is not a change in the display, by changing how values are written to the record with expect.addSnapshotSerializer(). In the example below, strings in the _r_0_ form are replaced with [useId] only when they are recorded.
// src/Field.test.tsx
import { render } from '@testing-library/react';
import { expect, test } from 'vitest';
import { EmailField } from './Field';
// Replace values like "_r_0_" that useId creates with a fixed string when recording
expect.addSnapshotSerializer({
test: (val) => typeof val === 'string' && /_r_[0-9a-z]+_/.test(val),
serialize: (val: string) => `"${val.replace(/_r_[0-9a-z]+_/g, '[useId]')}"`,
});
test('メールアドレスの欄', () => {
const { asFragment } = render(<EmailField />);
expect(asFragment()).toMatchSnapshot();
});
After I deleted the old .snap file and ran the tests, the .snap file contained for="[useId]" and id="[useId]". The tests passed even when I added another test before this one, and they also passed with CI=true.
A snapshot records the DOM as a string, so it cannot detect changes that only affect CSS. I changed the CSS file that the component loads with import './PriceTag.css'; to .badge { display: none; }, so the badge was no longer visible. The tests still passed. If you want to compare the appearance itself, the guide introduces a way to compare images with toMatchScreenshot() in browser mode.





