Tutorials JavaScript Testing with Jest
Ch 71 / 78
Chapter 71 Advanced 9 min read JavaScript

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.

What you'll learn
What Jest is and why developers use it
Setting up Jest in a Node.js project
Writing your first test with test() and expect()
Using common matchers — toBe, toEqual, toContain
Grouping tests with describe()
Testing async code — Promises & async/await
Mocking functions and modules with jest.fn()
Setup & teardown with beforeEach / afterEach

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.

Test Runner
Discovers, executes, and reports test files automatically — no manual wiring needed.
Assertion Library
Built-in expect() API with over 30 matchers for every scenario.
Mocking
Replace real dependencies with controlled fakes to isolate the code under test.
Coverage
Built-in Istanbul integration generates line, branch, and function coverage reports.

Setting Up Jest

Jest works with any Node.js project. Install it as a dev dependency, add a test script, and you're ready:

Terminal — Install Jest
# 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:

package.json
{
  "scripts": {
    "test": "jest",
    "test:watch": "jest --watch",
    "test:coverage": "jest --coverage"
  }
}
Pro Tip
Jest automatically finds test files named *.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 — Function to test
// 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 };
math.test.js — Test file
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');
});
Terminal — Run tests
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)
matchers-demo.test.js
// 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.

user.test.js
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.

beforeAll(fn)
Once before all tests in the describe block. Use for one-time expensive setup like starting a server or connecting to a DB.
beforeEach(fn)
Before each individual test. Use to reset state — e.g. create a fresh object, clear mocks, or seed test data.
afterEach(fn)
After each individual test. Use to clean up side effects — e.g. clear timers, restore mocks, delete temp files.
afterAll(fn)
Once after all tests. Use to close connections, remove test databases, or stop a server.
lifecycle.test.js
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);
});
⚡
Free Resource
Download our JavaScript Cheat Sheet
Syntax, built-in methods, ES6+ features — all on one page.
Get Sheet

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 to test
// 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 };
api.test.js — Three async test styles
// ✅ 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');
});
Common Mistake
If you forget to 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()
Creates a mock function that records how it was called — arguments, return values, call count.
jest.mock('module')
Auto-mocks an entire Node module. Every exported function becomes a jest.fn().
mockReturnValue()
Control exactly what a mock function returns, without running the real implementation.
spyOn()
Wraps an existing method so you can observe calls without replacing the real implementation.
mock-demo.test.js
// ─── 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
jest.mock() — Module mocking
// 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:

Terminal — Coverage report
npm test -- --coverage

# Sample output:
# ------------|---------|----------|---------|---------|
# File        | % Stmts | % Branch | % Funcs | % Lines |
# ------------|---------|----------|---------|---------|
# math.js     |     100 |      100 |     100 |     100 |
# user.js     |    87.5 |       75 |     100 |    87.5 |
# ------------|---------|----------|---------|---------|
Statements (%Stmts)
Percentage of individual statements in your code that were executed by tests.
Branches (%Branch)
Percentage of if/else branches, ternaries, and switch cases that were tested.
Functions (%Funcs)
Percentage of functions/methods that were called during the test run.
Lines (%Lines)
Percentage of executable lines that were run. HTML report highlights uncovered lines in red.

What Should You Test?

Not everything needs a test — but these patterns are always worth covering:

Pure functions
Edge cases (null, 0, empty)
Error paths
Data transformations
API response handling
Form validation logic
Auth / permission checks
Business-critical logic
Note
Aim for meaningful tests over high coverage numbers. A test that just calls a function without meaningful assertions gives you 100% coverage but zero confidence. Focus on behaviour, not lines.
Advertisement

Try It Yourself

Live Editor
✎ Editor
👁 Preview
Try it
This preview simulates a mini test runner in the browser. In a real project, Jest runs in Node.js from the terminal — but the concepts of expect(), matchers, and pass/fail output are identical.
Quick Check — Chapter 71

Which Jest matcher should you use to do a deep equality check on an object or array?

Chapter Summary
  • 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 jest and run with npm test.
  • Use test() / it() to define tests, and expect(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 / afterEach run before/after each test — use them to reset state.
  • For async code, use async/await in your test function. Use .resolves / .rejects for Promise assertions.
  • jest.fn() creates mock functions; jest.mock() mocks entire modules to isolate code under test.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel