Property Matchers for Dynamic Values
You'll learn how to keep snapshot tests reliable even when data like timestamps or IDs changes on every run.
The Problem with Dynamic Data
Snapshot tests capture the entire output of your code. But what happens when that output includes a timestamp, a randomly generated ID, or a database auto-increment value? Every test run produces different values, causing your snapshots to fail constantly—not because your logic broke, but because new Date() isn't the same millisecond twice.
How Property Matchers Work
Property matchers let you tell the snapshot system: "I expect this field to exist and be a certain type, but ignore its exact value." You provide an object that defines which properties should be matched by type instead of exact value.
test('user creation returns expected shape', () => {
const user = createUser('Alice');
expect(user).toMatchSnapshot({
id: expect.any(Number),
createdAt: expect.any(Date),
sessionToken: expect.any(String)
});
});
The snapshot stores placeholders like Any<Number> instead of the actual values. Your test verifies that id is a number, createdAt is a Date, and sessionToken is a string, while still snapshot-testing the rest of the object normally (like the name "Alice").
Think of It Like a Template
Imagine a form where most fields must match exactly, but a few fields just need to be "filled in with something valid." Property matchers create that flexible template for your snapshots.
// Snapshot will check name exactly, but allow any valid timestamp
expect(response).toMatchSnapshot({
timestamp: expect.any(Number)
});
Key Takeaway: Property matchers let you snapshot-test objects with dynamic values by verifying types instead of exact values, keeping tests stable without losing verification coverage.