Jest expect.toMatch Not Matching Fix
In this tutorial, you'll learn about Jest expect.toMatch Not Matching Fix. We cover key concepts, practical examples, and best practices.
Your expect(string).toMatch() assertion fails even though the string looks like it contains the expected text — or it matches when it shouldn't.
The Problem
// WRONG — case-sensitive matching
const errorMessage = 'User not found';
expect(errorMessage).toMatch('user not found'); // FAILS — case mismatch
Expected value to match: /user not found/
Received: "User not found"
toMatch() is case-sensitive by default. It also accepts both strings and regex patterns, which can lead to confusion.
Step-by-Step Fix
1. Use case-insensitive regex
// RIGHT — case-insensitive flag
expect('User not found').toMatch(/user not found/i);
// Passes — the /i flag makes it case-insensitive
2. Understand string vs regex arguments
// Both work, but differently:
expect('hello world').toMatch('hello'); // Passes — substring match
expect('hello world').toMatch(/^hello/); // Passes — regex anchor
expect('hello world').toMatch('HELLO'); // FAILS — case sensitive
expect('hello world').toMatch(/HELLO/i); // Passes — case insensitive
// Regex gives you anchors, quantifiers, and groups
expect('2024-01-01').toMatch(/^\d{4}-\d{2}-\d{2}$/);
expect('alice@example.com').toMatch(/^[\w.]+@\w+\.\w+$/);
3. Match against dynamic content
// RIGHT — partial match for dynamic strings
const result = `Order #${orderId} created successfully`;
expect(result).toMatch(/created successfully$/);
expect(result).toMatch(/Order #\d+/);
4. Use toContain for simple substring matching
// RIGHT — toContain is clearer for substring
expect('User alice@example.com logged in').toContain('logged in');
expect([1, 2, 3]).toContain(2); // Also works with arrays
Expected output:
PASS tests/match.test.js
✓ matches case-insensitive (3 ms)
✓ matches with regex (4 ms)
✓ uses toContain for subset (2 ms)
Prevention Tips
- Use regex with flags for case-insensitive matching
- Use
toContain()for simple substring checks - Use
toMatch(/^...$/)for exact string matching - Escape special regex characters in dynamic input
- Prefer
toContainovertoMatchfor readability
Common Mistakes with expect to match
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world JEST code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro