Unit testing verifies individual pieces of code (units) work as expected. Jest is a popular JavaScript testing framework focused on simplicity and support for modern JS features.

💡 Why Jest?
Jest requires minimal configuration, supports snapshots, mocks, and runs tests in parallel for speed.
Basic Jest Test Structure
Tests are organized in test or it blocks with descriptive names, containing assertions to validate code behavior.
📌 Deep Dive: Simple Test Example
test('adds 1 + 2 to equal 3', () => {
expect(1 + 2).toBe(3);
});
Key Jest Functions
test(name, fn): Defines a test case.describe(name, fn): Groups related tests.expect(value): Creates an assertion object.toBe(value): Checks strict equality.toEqual(value): Checks deep equality (objects/arrays).beforeEach(fn)/afterEach(fn): Setup/teardown hooks.
Testing Functions with Jest
Write tests that call your function and assert expected results.
📌 Deep Dive: Function Testing
function sum(a, b) {
return a + b;
}
test('sum adds two numbers', () => {
expect(sum(2, 3)).toBe(5);
});
Mock Functions
Jest can replace dependencies with mock functions to isolate testing and track calls.
📌 Deep Dive: Simple Mock Example
const mockCallback = jest.fn();
[1, 2, 3].forEach(mockCallback);
test('mock function called 3 times', () => {
expect(mockCallback.mock.calls.length).toBe(3);
});
⚠️ Test Isolation
Avoid sharing state between tests; use beforeEach or reset mocks to ensure independence.
Test File Naming and Running Tests
- Test files end with
.test.jsor.spec.js. - Run tests via
jestCLI ornpm testif configured. - Watch mode reruns tests on file changes for fast feedback.
| Matcher | Purpose |
|---|---|
toBe(value) | Strict equality (===) |
toEqual(value) | Value equality (objects/arrays) |
toBeTruthy() | Boolean true-like values |
toBeFalsy() | Boolean false-like values |
toContain(item) | Array or string contains |
toHaveBeenCalled() | Mock function called |
💡 Tip
Write small, focused tests that verify one piece of functionality clearly and independently.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Which Jest function defines a test case?
Question 2 of 2
What Jest matcher checks deep equality of objects or arrays?
Loading results...