What You'll Learn
You'll learn how to replace brittle snapshot tests with targeted, explicit assertions that clearly document what matters and survive harmless refactors.
The Problem with Snapshots
Snapshot tests compare everything—structure, classNames, even whitespace. When you change something trivial (like reordering props or adding a wrapper div), the snapshot breaks. The test doesn't explain what you're actually verifying, just that "something changed."
Explicit Assertions: Testing What Matters
Instead of snapshot-testing an entire component tree, query for the specific elements that represent user-facing behavior and assert their presence, content, or attributes explicitly.
Example: Rather than snapshotting a user profile card, explicitly check:
test('displays user information correctly', () => {
render(<UserCard user={{ name: 'Alice', email: 'alice@example.com' }} />);
expect(screen.getByRole('heading', { name: 'Alice' })).toBeInTheDocument();
expect(screen.getByText('alice@example.com')).toBeInTheDocument();
expect(screen.getByRole('img', { name: /alice/i })).toHaveAttribute('src', expect.stringContaining('avatar'));
});
This test survives if you add a CSS class, restructure divs, or reorder elements—because it only cares about the meaningful output.
Why This Matters
Explicit assertions document intent. Six months later, you'll understand why the test exists. They also pinpoint failures: "Expected heading not found" beats "Snapshot mismatch" with a 50-line diff.
Think of it like a contract: instead of requiring your component's entire internal structure match a template, you're only requiring specific guarantees about what users will see.
When to Use Which
Use explicit assertions for critical user-facing content. Reserve snapshots (if at all) for things like generated class lists in CSS-in-JS libraries where structure legitimately matters.
Key Takeaway: Query for specific elements and assert their presence or content explicitly—this documents intent and survives harmless changes.