String Matching Assertions
What you'll learn: How to assert that strings match exact values, contain specific substrings, or satisfy regex patterns in your tests.
When testing functions that return or manipulate strings, you need more than just equality checks. String matching assertions let you verify text in flexible ways: checking if a message contains a keyword, validating formats like email addresses, or ensuring exact text output.
Why String-Specific Assertions Matter
While toBe() works for exact matches, real-world scenarios often require partial or pattern-based validation. You might want to ensure an error message contains "unauthorized" without caring about the full text, or verify a generated ID matches a UUID pattern.
Common String Assertion Patterns
Exact matching uses the equality assertions you already know:
expect(result).toBe("Hello, World!");
Substring checks verify that a string contains specific text:
expect(errorMessage).toContain("not found");
expect(logOutput).toContain("success");
Regex pattern matching tests whether strings conform to patterns:
expect(email).toMatch(/^[^\s@]+@[^\s@]+\.[^\s@]+$/);
expect(uuid).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-/);
Choosing the Right Assertion
Use exact matching when the string must be identical. Use substring checks when you care about specific content but not the entire message. Use regex patterns when validating formats, structures, or flexible patterns.
Think of it like searching: exact match is "find this word only," substring is "find documents containing this word," and regex is "find documents matching this template."
Key Takeaway: String matching assertions let you verify text output with exact matches (toBe), partial content (toContain), or structural patterns (toMatch), giving you precision and flexibility in testing string-based behavior.