Script Valley
Node.js: The Complete Runtime
Databases, Testing, and DeploymentLesson 6.2

Unit testing Node.js with Jest

Jest setup, describe/it/expect, matchers, async tests, beforeEach/afterEach, mocking modules with jest.mock, mocking functions with jest.fn

Tests Give You Confidence to Refactor

Jest is the most popular Node.js testing framework. It requires zero configuration for CommonJS projects.

npm install jest --save-dev
// utils/math.js
function add(a, b) { return a + b; }
function divide(a, b) {
  if (b === 0) throw new Error('Division by zero');
  return a / b;
}
module.exports = { add, divide };
// utils/math.test.js
const { add, divide } = require('./math');

describe('add', () => {
  it('adds two positive numbers', () => {
    expect(add(2, 3)).toBe(5);
  });
  it('handles negative numbers', () => {
    expect(add(-1, 1)).toBe(0);
  });
});

describe('divide', () => {
  it('divides correctly', () => {
    expect(divide(10, 2)).toBe(5);
  });
  it('throws on division by zero', () => {
    expect(() => divide(10, 0)).toThrow('Division by zero');
  });
});

Testing Async Functions

it('fetches user data', async () => {
  const user = await getUser(1);
  expect(user).toMatchObject({ id: 1, name: expect.any(String) });
});

Up next

Integration testing Express APIs with Supertest

Sign in to track progress