Unit Testing TypeScript with Jest: A Beginner-Friendly Guide

2025-08-14

Unit Testing TypeScript with Jest: A Beginner-Friendly Guide

Quality code is code with confidence—and confidence comes from tests.

In this tutorial you will:

  1. Configure Jest for TypeScript using ts-jest.
  2. Write your first test and run coverage.
  3. Learn common mocking patterns (spies, modules, HTTP).
  4. Integrate tests in GitHub Actions CI.

1. Installation & Config

npm i -D jest ts-jest @types/jest

Initialize config:

npx ts-jest config:init

jest.config.js:

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  coverageDirectory: 'coverage',
  clearMocks: true,
};

2. Writing Your First Test

math.ts:

export const add = (a: number, b: number) => a + b;

math.test.ts:

import { add } from './math';

describe('add', () => {
  it('adds two numbers', () => {
    expect(add(2, 3)).toBe(5);
  });
});

Run:

npm test -- --watch

3. Mocking Examples

HTTP (axios)

jest.mock('axios');
import axios from 'axios';
// ... your test ...

Spying on Functions

const spy = jest.spyOn(console, 'log').mockImplementation(() => {});
expect(spy).toHaveBeenCalled();

4. Coverage Report

npm test -- --coverage

Outputs HTML report in coverage/—open index.html.

5. GitHub Actions CI

.github/workflows/test.yml:

name: CI
on: [push]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
      - run: npm ci
      - run: npm test -- --ci

Debugging Tips

  • Failing snapshot? Run npm test -- -u to update.
  • Tests running slow? Use --runInBand or increase Jest workers.

Happy testing!

← Back to Home