Learn the concept
Matchers and Assertions
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');
});
});Using `expect(result).toBe('expected_value')` for primitive values or `expect(object).toEqual({ ... })` for complex objects to ensure the function output matches the exact expected outcome.
Employing `expect(response.data).toMatchObject({ id: expect.any(Number), name: expect.any(String) })` to verify that the API response contains the required fields with their correct types, without needing to match the entire object.
Using `expect(() => dangerousFunction()).toThrow(MyCustomError)` or `expect(asyncCall()).rejects.toThrow('Error Message')` to confirm that error conditions are properly identified and handled.
Create a JavaScript utility file with functions for string manipulation (e.g., reverse, capitalize, check palindrome) and write Jest tests for each using various string matchers like `toMatch`, `toContain`, and `toHaveLength`.
Simulate an API call that returns a JSON object. Write Jest tests using `toEqual`, `toMatchObject`, and `toHaveProperty` to validate the structure and content of the simulated API response.
React Testing Library, which often uses Jest as its test runner, leverages Jest matchers extensively for asserting DOM changes and component behavior. Matchers like `toBeInTheDocument()`, `toHaveTextContent()`, and `toBeDisabled()` (custom matchers from `@testing-library/jest-dom`) build upon Jest's core assertion capabilities to provide semantic UI tests.
Storybook's Interaction Tests feature often integrates with Jest, allowing developers to write tests that interact with UI components in a browser-like environment and then use Jest matchers to assert the state and behavior of the components after interactions.