Jest is a delightful JavaScript testing framework with a focus on simplicity, zero-config setups, and instant snapshot testing.
Test Execution & CLI Flags
jest # Run all tests
jest --watch # Run tests in interactive watch mode
jest --coverage # Generate code coverage report
jest path/to/test.js # Run specific test file
jest -t "test name pattern" # Filter tests by description string
jest --runInBand # Run tests serially in a single process
Common Matchers
// Truthiness & Equality
expect(val).toBe(42); // Strict equality (Object.is)
expect(val).toEqual({ a: 1 }); // Deep structural equality
expect(val).toStrictEqual({ a: 1 }); // Checks type prototypes as well
expect(val).toBeNull();
expect(val).toBeDefined();
expect(val).toBeTruthy();
expect(val).toBeFalsy();
// Numbers
expect(val).toBeGreaterThan(3);
expect(val).toBeGreaterThanOrEqual(3.5);
expect(val).toBeCloseTo(0.3, 5); // Floating point arithmetic comparison
// Strings & Arrays
expect(str).toMatch(/regex/);
expect(arr).toContain('item');
expect(arr).toHaveLength(3);
// Exceptions
expect(() => compileCode()).toThrow();
expect(() => compileCode()).toThrow(ConfigError);
Asynchronous Code
test('resolves with data', async () => {
const data = await fetchData();
expect(data).toHaveProperty('status', 200);
});
test('handles promise rejection', async () => {
await expect(fetchData('invalid')).rejects.toThrow('Not Found');
});
Mock Functions (jest.fn() & Spies)
const mockFn = jest.fn().mockReturnValue('mocked result');
mockFn('arg1');
expect(mockFn).toHaveBeenCalledTimes(1);
expect(mockFn).toHaveBeenCalledWith('arg1');
// Mocking module methods
const spy = jest.spyOn(api, 'getUser').mockResolvedValue({ id: 1, name: 'Alice' });
const user = await api.getUser(1);
expect(spy).toHaveBeenCalled();
spy.mockRestore(); // Restore original implementation
Snapshot Testing
test('renders correctly', () => {
const tree = renderer.create(<Button label="Submit" />).toJSON();
expect(tree).toMatchSnapshot();
});
Setup and Teardown
beforeAll(() => database.connect());
afterAll(() => database.disconnect());
beforeEach(() => database.clear());
afterEach(() => jest.clearAllMocks());