On this page

Unit Testing

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

Unit testing in TypeScript is not just about running tests—it’s about getting type‑safe tests, catching mistakes before runtime, and ensuring your code behaves exactly as intended.

In this lesson, we’ll cover the two most popular testing stacks in the TypeScript ecosystem:

Both support TypeScript beautifully, but they take different approaches.

Let’s break them down.


Why Testing in TypeScript Is Special​

TypeScript gives you two layers of safety:

  1. Static safety → Type errors caught before running tests
  2. Runtime safety → Tests verifying behavior

A good TS testing setup ensures:

This is why choosing the right test runner matters.


Jest with TypeScript​

Jest is the most widely used JavaScript testing framework.

To use it with TypeScript, you need a transformer—historically ts-jest, now often babel-jest.

We’ll use ts-jest because it gives the best TypeScript integration.


1. Install Jest + ts-jest​


npm install --save-dev jest ts-jest @types/jest

Initialize:


npx ts-jest config:init

This generates:

jest.config.js​


module.exports = {

  preset: "ts-jest",

  testEnvironment: "node",

};

2. Write a Simple Test​

src/math.ts​


export function add(a: number, b: number) {

  return a + b;

}

src/math.test.ts​


import { add } from "./math";



test("adds numbers", () => {

  expect(add(2, 3)).toBe(5);

});

3. Run Jest​


npx jest

Jest will:


4. Type‑Safe Jest Assertions​

Jest’s types ensure:


expect(add(2, 3)).toBe("5");

// ❌ Type error before test even runs

This is a huge advantage over plain JS.


5. Mocking with Type Safety​


const fetchUser = jest.fn<Promise<string>, []>(() => Promise.resolve("Alice"));

Jest’s generics let you type:


Pros of Jest​


Cons of Jest​


Vitest with TypeScript​

Vitest is the modern alternative—built by the Vite team.

It’s fast, lightweight, and deeply TypeScript‑friendly.

Vitest is now the default choice for many new TS projects.


1. Install Vitest​


npm install --save-dev vitest

If using Vite:


npm install --save-dev @vitejs/plugin-react # or vue, svelte, etc.

2. Add a Vitest Config​

vite.config.ts


import { defineConfig } from "vite";

import { resolve } from "path";



export default defineConfig({

  test: {

    globals: true,

    environment: "node",

  },

});

Vitest integrates directly with Vite’s config.


3. Write a Test​

src/math.test.ts


import { describe, it, expect } from "vitest";

import { add } from "./math";



describe("add", () => {

  it("adds numbers", () => {

    expect(add(2, 3)).toBe(5);

  });

});

4. Run Vitest​


npx vitest

Or watch mode:


npx vitest --watch

Vitest is extremely fast—often 10–20× faster than Jest.


5. Type‑Safe Assertions​

Vitest uses @types/jest‑style matchers:


expect(add(2, 3)).toBe("5");

// ❌ Type error

Same safety as Jest, but faster.


6. Mocking in Vitest​

Vitest has a Jest‑compatible mocking API:


import { vi } from "vitest";



const fetchUser = vi.fn(() => "Alice");

Or typed:


const fetchUser = vi.fn<[], string>(() => "Alice");

Pros of Vitest​


Cons of Vitest​


Jest vs Vitest: Quick Comparison​

FeatureJestVitestSpeedMediumVery fastESM supportPartialExcellentTypeScript supportGoodExcellentMockingExcellentExcellentConfigHeavyLightBest forEnterprise, legacyModern TS, Vite apps


Recommended Setup​

For modern TypeScript projects​

→ Vitest

For enterprise or legacy Node projects​

→ Jest


Summary​

In this lesson, you learned how to test TypeScript using two major frameworks:

1. Jest + TypeScript​

2. Vitest + TypeScript​

Both give you type‑safe tests, ensuring correctness before runtime.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Testing TypeScript

Next

Type Testing