Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Jest is a delightful JavaScript testing framework maintained by Facebook. It works with zero configuration for most projects and provides a complete testing solution.
Parallel test execution
Assertions, mocks, spies
Works out of the box
Test UI components
npm install --save-dev jest"test": "jest"// math.js
function add(a, b) {
return a + b;
}
module.exports = { add };
// math.test.js
const { add } = require('./math');
test('adds 1 + 2 to equal 3', () => {
expect(add(1, 2)).toBe(3);
});
test('adds negative numbers', () => {
expect(add(-1, -2)).toBe(-3);
});
// Run: npm testexpect(value).toBe(5)Strict equality (===)
expect(obj).toEqual({...})Deep equality
expect(value).toBeTruthy()Any truthy value
expect(value).toBeNull()Matches null only
expect(n).toBeGreaterThan(3)Greater than comparison
expect(n).toBeCloseTo(0.3)Floating point equality
expect(str).toMatch(/pattern/)Regex matching
expect(arr).toContain(item)Array includes item
test('matchers examples', () => {
// Equality
expect(2 + 2).toBe(4);
expect({ name: 'Alice' }).toEqual({ name: 'Alice' });
// Truthiness
expect(null).toBeNull();
expect(undefined).toBeUndefined();
expect('hello').toBeTruthy();
expect(0).toBeFalsy();
// Numbers
expect(10).toBeGreaterThan(5);
expect(10).toBeGreaterThanOrEqual(10);
expect(0.1 + 0.2).toBeCloseTo(0.3); // Floating point
// Strings
expect('Hello World').toMatch(/World/);
expect('test@example.com').toMatch(/^\w+@\w+\.\w+$/);
// Arrays
const fruits = ['apple', 'banana', 'orange'];
expect(fruits).toContain('banana');
expect(fruits).toHaveLength(3);
// Objects
const user = { name: 'John', age: 30 };
expect(user).toHaveProperty('name');
expect(user).toHaveProperty('age', 30);
});// calculator.js
class Calculator {
add(a, b) { return a + b; }
subtract(a, b) { return a - b; }
multiply(a, b) { return a * b; }
divide(a, b) {
if (b === 0) throw new Error('Division by zero');
return a / b;
}
}
module.exports = Calculator;
// calculator.test.js
const Calculator = require('./calculator');
describe('Calculator', () => {
let calc;
// Runs before each test
beforeEach(() => {
calc = new Calculator();
});
describe('addition', () => {
test('adds positive numbers', () => {
expect(calc.add(2, 3)).toBe(5);
});
test('adds negative numbers', () => {
expect(calc.add(-2, -3)).toBe(-5);
});
});
describe('division', () => {
test('divides numbers', () => {
expect(calc.divide(10, 2)).toBe(5);
});
test('throws error on division by zero', () => {
expect(() => calc.divide(10, 0)).toThrow('Division by zero');
});
});
});Runs before each test in the suite
Use for: Setup common test dataRuns after each test completes
Use for: Cleanup, reset stateRuns once before all tests
Use for: Expensive setup (DB connection)Runs once after all tests
Use for: Final cleanup (close connections)// api.js
async function fetchUser(id) {
const response = await fetch(`/api/users/${id}`);
return response.json();
}
// api.test.js
// Method 1: async/await
test('fetches user data', async () => {
const user = await fetchUser(1);
expect(user.name).toBe('John Doe');
});
// Method 2: return promise
test('fetches user with promise', () => {
return fetchUser(1).then(user => {
expect(user.name).toBe('John Doe');
});
});
// Method 3: resolves matcher
test('fetches user with resolves', async () => {
await expect(fetchUser(1)).resolves.toHaveProperty('name', 'John Doe');
});
// Testing rejections
test('handles errors', async () => {
await expect(fetchUser(-1)).rejects.toThrow('User not found');
});// Basic mock function
test('mock function basics', () => {
const mockFn = jest.fn();
// Call the mock
mockFn('hello');
mockFn('world');
// Assertions
expect(mockFn).toHaveBeenCalled();
expect(mockFn).toHaveBeenCalledTimes(2);
expect(mockFn).toHaveBeenCalledWith('hello');
expect(mockFn).toHaveBeenLastCalledWith('world');
});
// Mock with return value
test('mock with return value', () => {
const mockFn = jest.fn().mockReturnValue(42);
expect(mockFn()).toBe(42);
expect(mockFn()).toBe(42); // Always returns 42
});
// Mock implementation
test('mock implementation', () => {
const mockFn = jest.fn((x, y) => x + y);
expect(mockFn(2, 3)).toBe(5);
});
// Mock resolved value (for promises)
test('mock async function', async () => {
const mockFn = jest.fn().mockResolvedValue({ data: 'success' });
const result = await mockFn();
expect(result.data).toBe('success');
});// Link.js
function Link({ page, children }) {
return <a href={page}>{children}</a>;
}
// Link.test.js
import renderer from 'react-test-renderer';
import Link from './Link';
test('Link renders correctly', () => {
const tree = renderer
.create(<Link page="https://example.com">Example</Link>)
.toJSON();
expect(tree).toMatchSnapshot();
// Creates __snapshots__/Link.test.js.snap
});
// Inline snapshots (no separate file)
test('inline snapshot', () => {
const data = { name: 'John', age: 30 };
expect(data).toMatchInlineSnapshot(`
{
"age": 30,
"name": "John",
}
`);
});module.exports = {
testEnvironment: 'node', // or 'jsdom' for browser
coverageThreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: 80
}
},
testMatch: ['**/__tests__/**/*.js', '**/?(*.)+(spec|test).js'],
collectCoverageFrom: ['src/**/*.js'],
setupFilesAfterEnv: ['<rootDir>/jest.setup.js']
};Works out of the box
Just run npm test
toBe, toEqual, toContain, etc.
Expressive assertions
jest.fn(), mock modules
No extra libraries needed
Test UI components easily
Auto-detect changes
npm install --save-dev jestnpm test - Jest will find and run all *.test.js files!