Jest matchers are methods used with expect() to test values. Common ones include toBe() for exact equality, toEqual() for deep equality, toBeTruthy()/toBeFalsy() for boolean checks, toContain() for arrays/strings, and toThrow() for errors.
Equality Matchers:
toBe(): Exact equality (===, same reference)toEqual(): Deep equality (for objects/arrays)toStrictEqual(): Strict deep equality (checks undefined)Truthiness:
toBeTruthy() / toBeFalsy()toBeNull() / toBeUndefined() / toBeDefined()Numbers:
toBeGreaterThan() / toBeLessThan()toBeCloseTo(): For floating pointStrings:
toMatch(): Regex matchingtoContain(): Substring checkArrays/Iterables:
toContain(): Item in arraytoHaveLength(): Array/string lengthObjects:
toHaveProperty(): Check property existstoMatchObject(): Partial object matchingdescribe('Jest matchers', () => {
// Equality
test('toBe vs toEqual', () => {
expect(2 + 2).toBe(4); // Exact equality
expect({ a: 1 }).toEqual({ a: 1 }); // Deep equality
expect({ a: 1 }).not.toBe({ a: 1 }); // Different references!
});
// Truthiness
test('truthiness', () => {
expect(true).toBeTruthy();
expect(0).toBeFalsy();
expect(null).toBeNull();
expect(undefined).toBeUndefined();
expect('value').toBeDefined();
});
// Numbers
test('numbers', () => {
expect(10).toBeGreaterThan(5);
expect(5).toBeLessThanOrEqual(5);
expect(0.1 + 0.2).toBeCloseTo(0.3); // Floating point!
});
// Strings
test('strings', () => {
expect('hello world').toMatch(/world/);
expect('hello world').toContain('world');
});
// Arrays
test('arrays', () => {
expect([1, 2, 3]).toContain(2);
expect([1, 2, 3]).toHaveLength(3);
expect(['apple', 'banana']).toContainEqual('banana');
});
});