Jest Introduction - JavaScript Testing Basics

intermediate | 50 min read | 2024.12.23

What You’ll Learn in This Tutorial

✓ Jest setup
✓ Writing basic tests
✓ Matchers (assertions)
✓ Mocks and spies
✓ Async testing
✓ Coverage reports

Step 1: Setup

npm init -y
npm install -D jest @types/jest ts-jest typescript
npx ts-jest config:init

jest.config.js

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  testMatch: ['**/*.test.ts'],
  collectCoverageFrom: ['src/**/*.ts'],
};

Step 2: Basic Tests

// src/math.ts
export function add(a: number, b: number): number {
  return a + b;
}

export function divide(a: number, b: number): number {
  if (b === 0) throw new Error('Division by zero');
  return a / b;
}

// src/math.test.ts
import { add, divide } from './math';

describe('Math functions', () => {
  describe('add', () => {
    it('should add two numbers', () => {
      expect(add(1, 2)).toBe(3);
    });

    it('should handle negative numbers', () => {
      expect(add(-1, 1)).toBe(0);
    });
  });

  describe('divide', () => {
    it('should divide two numbers', () => {
      expect(divide(10, 2)).toBe(5);
    });

    it('should throw error for division by zero', () => {
      expect(() => divide(10, 0)).toThrow('Division by zero');
    });
  });
});

Step 3: Matchers

// Equality
expect(value).toBe(3);           // Strict equality
expect(obj).toEqual({ a: 1 });   // Object comparison

// Boolean
expect(value).toBeTruthy();
expect(value).toBeFalsy();
expect(value).toBeNull();
expect(value).toBeDefined();

// Numbers
expect(value).toBeGreaterThan(3);
expect(value).toBeLessThanOrEqual(5);
expect(0.1 + 0.2).toBeCloseTo(0.3);

// Strings
expect(str).toMatch(/pattern/);
expect(str).toContain('substring');

// Arrays
expect(arr).toContain(item);
expect(arr).toHaveLength(3);

Step 4: Mocks

// src/userService.ts
import { db } from './db';

export async function getUser(id: number) {
  return db.user.findById(id);
}

// src/userService.test.ts
import { getUser } from './userService';
import { db } from './db';

jest.mock('./db');

describe('UserService', () => {
  it('should return user', async () => {
    const mockUser = { id: 1, name: 'Test' };
    (db.user.findById as jest.Mock).mockResolvedValue(mockUser);

    const result = await getUser(1);
    expect(result).toEqual(mockUser);
    expect(db.user.findById).toHaveBeenCalledWith(1);
  });
});

Step 5: Async Testing

// async/await
it('should fetch data', async () => {
  const data = await fetchData();
  expect(data).toBeDefined();
});

// Promises
it('should resolve', () => {
  return expect(asyncFunc()).resolves.toBe('value');
});

it('should reject', () => {
  return expect(asyncFunc()).rejects.toThrow();
});

Step 6: Running Tests

# Run tests
npm test

# Watch mode
npm test -- --watch

# Coverage
npm test -- --coverage

Summary

Jest is an easy-to-use test framework with rich mocking features. Writing tests improves code quality and reliability.

← Back to list