Custom Matchers in Jest
From the Jest cheat sheet · Matchers · verified Jul 2026
Custom Matchers
Creating your own Jest matchers for domain-specific assertions
typescript
// Define custom matcher
expect.extend({
toBeWithinRange(received, floor, ceiling) {
const pass = received >= floor && received <= ceiling
if (pass) {
return {
message: () =>
\`expected \${received} not to be within range \${floor} - \${ceiling}\`,
pass: true,
}
} else {
return {
message: () =>
\`expected \${received} to be within range \${floor} - \${ceiling}\`,
pass: false,
}
}
},
})
// Use custom matcher
test('numeric ranges', () => {
expect(100).toBeWithinRange(90, 110)
expect(101).not.toBeWithinRange(0, 100)
})💡 Custom matchers improve test readability for domain logic
⚡ Add TypeScript definitions for autocomplete support
📌 Use setupFilesAfterEnv to load matchers globally
🟢 Asymmetric matchers allow flexible partial matching
matcherscustomadvanced