Testing with Jest
Jest is the most popular JavaScript testing framework — zero-config, fast, and batteries-included. Learn how to write unit tests, use powerful matchers, mock dependencies, and test async code like a professional.
test() and expect()
describe()jest.fn()What is Jest?
Jest is an open-source JavaScript testing framework developed and maintained by Meta (Facebook). It is designed to work out of the box for most JavaScript projects — React, Node.js, TypeScript, Vue, and more — with zero configuration required for typical setups.
Jest bundles everything you need for testing into a single package: a test runner, an assertion library, mock utilities, code coverage reports, and a watch mode that only re-runs affected tests. It's the most downloaded testing library on npm.
expect() API with
over 30 matchers for every scenario.Setting Up Jest
Jest works with any Node.js project. Install it as a dev dependency, add a test script, and you're ready:
# 1 — Initialise a new project (skip if you already have package.json)
npm init -y
# 2 — Install Jest as a dev dependency
npm install --save-dev jest
# 3 — (Optional) Install Babel support for ES modules
npm install --save-dev babel-jest @babel/core @babel/preset-env
Add a test
script to your package.json:
{
"scripts": {
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage"
}
}
*.test.js, *.spec.js, or files inside a __tests__ folder. No config file needed for basic projects.
Your First Test
A Jest test has three parts: a description, an
action (calling the function you're testing), and an assertion
(checking the result). The two core globals are test() (or
it()) and expect().
// math.js — the code we want to test
function add(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
module.exports = { add, multiply };
const { add, multiply } = require('./math');
// test() takes a description string and a function
test('adds 2 + 3 to equal 5', () => {
expect(add(2, 3)).toBe(5);
});
test('multiplies 4 × 5 to equal 20', () => {
expect(multiply(4, 5)).toBe(20);
});
// it() is an alias for test() — same behaviour
it('returns a number type', () => {
expect(typeof add(1, 2)).toBe('number');
});
npm test
# Output:
# PASS math.test.js
# ✓ adds 2 + 3 to equal 5 (3 ms)
# ✓ multiplies 4 × 5 to equal 20 (1 ms)
# ✓ returns a number type (0 ms)
#
# Tests: 3 passed, 3 total
Common Matchers
Matchers are the chainable methods on expect() that describe what you expect the value to be. Jest
ships with a rich set of matchers for every data type:
| Matcher | What it checks | Example |
|---|---|---|
| .toBe(val) | Strict equality (===) — primitives |
expect(1+1).toBe(2) |
| .toEqual(val) | Deep equality — objects, arrays | expect({a:1}).toEqual({a:1}) |
| .toBeTruthy() | Value is truthy | expect("hello").toBeTruthy() |
| .toBeFalsy() | Value is falsy | expect(0).toBeFalsy() |
| .toBeNull() | Value is exactly null |
expect(null).toBeNull() |
| .toBeUndefined() | Value is undefined |
expect(undefined).toBeUndefined() |
| .toContain(item) | Array / string contains item | expect([1,2,3]).toContain(2) |
| .toHaveLength(n) | Array / string has length n | expect("abc").toHaveLength(3) |
| .toThrow() | Function throws an error | expect(fn).toThrow() |
| .toMatch(regex) | String matches regex/pattern | expect("Jest").toMatch(/jest/i) |
| .toBeGreaterThan(n) | Number > n | expect(10).toBeGreaterThan(5) |
| .not.matcher() | Negates any matcher | expect(5).not.toBe(10) |
// Primitive — use toBe
expect(2 + 2).toBe(4);
// Object — use toEqual (deep comparison)
const user = { name: 'Raj', age: 25 };
expect(user).toEqual({ name: 'Raj', age: 25 });
// Array
const fruits = ['mango', 'banana', 'kiwi'];
expect(fruits).toContain('banana');
expect(fruits).toHaveLength(3);
// Negation with .not
expect('hello').not.toBe('world');
// Error throwing
function boom() { throw new Error('Kaboom!'); }
expect(boom).toThrow('Kaboom!');
Grouping Tests with describe()
describe() lets you group related tests
into a test suite. This keeps your test output organised and lets you share
setup/teardown logic within a group. Suites can even be nested.
const { getUserName, isAdmin } = require('./user');
// describe() groups related tests — name shows in output
describe('getUserName()', () => {
it('returns the user name', () => {
expect(getUserName({ name: 'Priya' })).toBe('Priya');
});
it('returns Unknown for missing name', () => {
expect(getUserName({})).toBe('Unknown');
});
});
describe('isAdmin()', () => {
it('returns true for admin role', () => {
expect(isAdmin({ role: 'admin' })).toBe(true);
});
it('returns false for regular user', () => {
expect(isAdmin({ role: 'user' })).toBe(false);
});
});
Setup & Teardown
Jest provides lifecycle hooks to run code before or after tests. This is essential for setting up database connections, creating test fixtures, or resetting state between tests.
let counter;
beforeAll(() => {
console.log('🚀 Suite starting');
});
beforeEach(() => {
counter = 0; // reset before every test
});
afterEach(() => {
console.log('Counter after test:', counter);
});
afterAll(() => {
console.log('✅ Suite complete');
});
test('counter starts at 0', () => {
expect(counter).toBe(0);
});
test('incrementing counter', () => {
counter++;
expect(counter).toBe(1);
});
Testing Async Code
Real-world functions are often asynchronous — they fetch data, read files, or query databases. Jest handles async tests in three ways: callbacks, Promises, and async/await. The async/await approach is the most readable:
// api.js
async function fetchUser(id) {
const res = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
if (!res.ok) throw new Error('User not found');
return res.json();
}
module.exports = { fetchUser };
// ✅ Style 1 — return the Promise (Jest waits for it)
test('fetches user via Promise', () => {
return fetchUser(1).then(user => {
expect(user.id).toBe(1);
});
});
// ✅ Style 2 — async / await (cleanest)
test('fetches user with async/await', async () => {
const user = await fetchUser(1);
expect(user.name).toBeDefined();
expect(user.id).toBe(1);
});
// ✅ Style 3 — test rejection (error path)
test('throws for invalid user id', async () => {
await expect(fetchUser(9999)).rejects.toThrow('User not found');
});
return a Promise or use await, Jest will complete the test before the
async code runs — and the test will pass even if your assertion would have failed!
Mocking with jest.fn()
Mocking lets you replace real dependencies with controlled fakes, so you can
test a function in isolation — without hitting the network, filesystem, or
database. Jest provides two key tools: jest.fn() for
individual functions and jest.mock() for entire modules.
jest.fn().// ─── Basic jest.fn() ───────────────────────────────────────
const greet = jest.fn(() => 'Hello!');
greet('Raj');
greet('Priya');
expect(greet).toHaveBeenCalledTimes(2);
expect(greet).toHaveBeenCalledWith('Raj');
expect(greet).toHaveBeenLastCalledWith('Priya');
// ─── mockReturnValue ───────────────────────────────────────
const getUser = jest.fn();
getUser.mockReturnValue({ id: 1, name: 'Arjun' });
const user = getUser();
expect(user.name).toBe('Arjun');
// ─── jest.spyOn() ──────────────────────────────────────────
const calculator = { add: (a, b) => a + b };
const spy = jest.spyOn(calculator, 'add');
calculator.add(3, 4);
expect(spy).toHaveBeenCalledWith(3, 4);
spy.mockRestore(); // restore original implementation
// Auto-mock the entire 'axios' module
jest.mock('axios');
const axios = require('axios');
test('fetches user data', async () => {
// Control what axios.get() returns
axios.get.mockResolvedValue({
data: { id: 1, name: 'Meera' }
});
const res = await axios.get('/users/1');
expect(res.data.name).toBe('Meera');
expect(axios.get).toHaveBeenCalledWith('/users/1');
});
Code Coverage
Coverage measures how much of your source code is executed during tests. Jest integrates Istanbul to generate detailed reports. Run coverage with:
npm test -- --coverage
# Sample output:
# ------------|---------|----------|---------|---------|
# File | % Stmts | % Branch | % Funcs | % Lines |
# ------------|---------|----------|---------|---------|
# math.js | 100 | 100 | 100 | 100 |
# user.js | 87.5 | 75 | 100 | 87.5 |
# ------------|---------|----------|---------|---------|
What Should You Test?
Not everything needs a test — but these patterns are always worth covering:
Try It Yourself
expect(),
matchers, and pass/fail output are identical.
Which Jest matcher should you use to do a deep equality check on an object or array?
- Jest is a zero-config JavaScript testing framework by Meta with a built-in runner, assertions, mocks, and coverage.
- Install with
npm install --save-dev jestand run withnpm test. - Use
test()/it()to define tests, andexpect(value).matcher()to assert results. - toBe checks strict equality; toEqual does deep comparison for objects and arrays.
- describe() groups related tests into a suite for better organisation and shared setup.
beforeEach/afterEachrun before/after each test — use them to reset state.- For async code, use
async/awaitin your test function. Use.resolves/.rejectsfor Promise assertions. jest.fn()creates mock functions;jest.mock()mocks entire modules to isolate code under test.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.