Jest Guide

JestJavaScript Testing Framework

Learn unit testing, mocking, async testing, snapshots, and building reliable test suites with Jest.

Contents

Jest Basics

Jest is a JavaScript testing framework. Write tests with describe, test/it, and expect assertions.

bash
# Installation
npm install --save-dev jest

# Run Tests
npm test
npx jest
javascript
// math.js
function add(a, b) {
  return a + b;
}

function subtract(a, b) {
  return a - b;
}

module.exports = { add, subtract };

// math.test.js
const { add, subtract } = require('./math');

describe('Math functions', () => {
  test('adds 1 + 2 to equal 3', () => {
    expect(add(1, 2)).toBe(3);
  });

  test('subtracts 5 - 3 to equal 2', () => {
    expect(subtract(5, 3)).toBe(2);
  });
});

// Using it instead of test
it('should add two numbers', () => {
  expect(add(2, 3)).toBe(5);
});