Last Updated: November 21, 2025
Basic Test Structure
// math.test.js
describe('Math operations', () => {
test('adds 1 + 2 to equal 3', () => {
expect(1 + 2).toBe(3);
});
it('subtracts 5 - 2 to equal 3', () => {
expect(5 - 2).toBe(3);
});
});
// Setup and teardown
describe('Database tests', () => {
beforeAll(() => {
// Runs once before all tests
return initializeDatabase();
});
beforeEach(() => {
// Runs before each test
return clearDatabase();
});
afterEach(() => {
// Runs after each test
});
afterAll(() => {
// Runs once after all tests
return closeDatabase();
});
});
Matchers
| Matcher | Description |
|---|---|
toBe()
|
Strict equality (===) |
toEqual()
|
Deep equality |
toBeTruthy()/toBeFalsy()
|
Truthy/falsy check |
toBeNull()
|
Check for null |
toBeUndefined()
|
Check for undefined |
toContain()
|
Array/string contains item |
toHaveLength()
|
Check array/string length |
toThrow()
|
Function throws error |
Async Testing
// Promises
test('fetches user data', () => {
return fetchUser().then(data => {
expect(data.name).toBe('John');
});
});
// Async/Await
test('fetches user data', async () => {
const data = await fetchUser();
expect(data.name).toBe('John');
});
// Resolves/Rejects
test('promise resolves', () => {
return expect(fetchUser()).resolves.toBe('data');
});
test('promise rejects', () => {
return expect(fetchError()).rejects.toThrow('error');
});
Mocking
// Mock functions
const mockFn = jest.fn();
mockFn.mockReturnValue(42);
mockFn.mockResolvedValue('async value');
expect(mockFn).toHaveBeenCalled();
expect(mockFn).toHaveBeenCalledWith(arg1, arg2);
expect(mockFn).toHaveBeenCalledTimes(2);
// Mock modules
jest.mock('./api');
const { fetchData } = require('./api');
fetchData.mockResolvedValue({ data: 'mocked' });
// Spy on methods
const spy = jest.spyOn(object, 'method');
expect(spy).toHaveBeenCalled();
spy.mockRestore();
Snapshot Testing
import renderer from 'react-test-renderer';
import Component from './Component';
test('renders correctly', () => {
const tree = renderer
.create(<Component />)
.toJSON();
expect(tree).toMatchSnapshot();
});
// Update snapshots: jest -u
💡 Pro Tip:
Use describe.only() and test.only() to run specific tests during development!