HTML Snapshot Testing
Catch unintended HTML changes with snapshot tests.
What Snapshot Testing Is
Snapshot testing records the rendered output of a component or page on first run, then on subsequent runs compares the new output to the saved snapshot. Any change in HTML output causes the test to fail until the snapshot is intentionally updated.
Jest Snapshot Testing
Jest's toMatchSnapshot() matcher serializes a value (including JSX rendered to HTML) and compares to a saved file. npx jest -u updates snapshots when intentional changes happen. Tests serve as a regression net for accidental rendering changes.
import { render } from "@testing-library/react";
import Button from "./Button";
test("Button renders consistently", () => {
const { container } = render(<Button>Save</Button>);
expect(container.innerHTML).toMatchSnapshot();
});All lessons in this course
- The W3C Markup Validator
- Lighthouse HTML Audit
- Pa11y and axe for Accessibility Testing
- HTML Snapshot Testing