Matchers in Jest are methods used to assert values in your tests. They allow you to check whether a value meets certain conditions and are used with expect().
1️⃣ Basic Syntax
expect(value).matcher(expected);
value→ the actual resultmatcher→ function to test the valueexpected→ the expected outcome
2️⃣ Common Matchers
Equality Matchers
expect(2 + 2).toBe(4); // strict equality (===)
expect({a:1}).toEqual({a:1}); // deep equality for objects/arrays
Truthiness Matchers
expect(null).toBeNull();
expect(undefined).toBeUndefined();
expect(true).toBeTruthy();
expect(false).toBeFalsy();
Number Matchers
expect(10).toBeGreaterThan(5);
expect(10).toBeLessThan(20);
expect(10).toBeGreaterThanOrEqual(10);
expect(10).toBeLessThanOrEqual(10);
expect(0.2 + 0.1).toBeCloseTo(0.3, 5);
String Matchers
expect("Hello World").toMatch(/World/);
expect("abc").toContain("b");
Array/Iterable Matchers
expect([1, 2, 3]).toContain(2);
expect([{a:1}]).toContainEqual({a:1});
Error Matchers
const throwError = () => { throw new Error("Oops"); };
expect(throwError).toThrow("Oops");
3️⃣ Negation
- You can negate matchers using
.not:
expect(5).not.toBe(3);
expect([1,2,3]).not.toContain(4);
⚡ Key Points:
- Matchers are the core of Jest assertions
- Use
.toBefor primitives,.toEqualfor objects/arrays - Support numbers, strings, arrays, objects, functions, errors
- Negation (
.not) allows opposite assertions
In short:
Matchers in Jest are methods to assert conditions in tests, making it easy to verify expected outcomes for variables, functions, and components.