Skip to content
Tutorials Center
My learning

Topics

Lesson 73 of 96 ยท TypeScript in Practice

Testing TypeScript with Jest and Vitest

Learn to test TypeScript code with Jest (ts-jest) and Vitest - setup, typed assertions, typed mocks and spies, testing types with expectTypeOf, and what type checking does not cover.

Types catch a whole class of mistakes, but they cannot tell you whether calculateDiscount(100, 'GOLD') returns the right number. For that you need tests. In the TypeScript world two test runners dominate: Jest, the long-standing default, and Vitest, a newer runner that shares Jest's API and is built around modern tooling. Both work well with TypeScript, and the tests you write for one are very close to the tests you write for the other.

This lesson explains how a TypeScript test setup works, how to write tests that stay type-safe, how to type mocks and spies, how to test the types themselves, and where type checking and testing each stop. The test runners cannot run inside this website's editor (they are tools that need Node packages and a file system), so the setup files are shown read-only. The examples you can run use a tiny hand-written test/expect stand-in, so you can see the same ideas in action. For the surrounding tooling, see Tooling and tsconfig.

How tests run TypeScript

A test runner is a Node program, and Node does not understand types. Something must remove them before the code runs. This is the first thing that differs between the two tools.

  • Vitest uses Vite's transformer, which strips types and compiles the file without checking it. It is fast, but a test with a type error still runs. You see the type errors from your editor and from tsc --noEmit, not from the test run.
  • Jest has no TypeScript support of its own. You choose a transformer: ts-jest compiles with the TypeScript compiler and reports type errors as test failures, while fast alternatives (@swc/jest, babel-jest with the TypeScript preset) strip types without checking, like Vitest.

So "the tests pass" does not automatically mean "the types are right". In a typical project you run both: the runner for behavior and tsc --noEmit for types.

flowchart LR
    T["math.test.ts"] --> S{"Transformer"}
    S -- "Vitest, SWC, Babel:<br/>strip types" --> R["Run in Node"]
    S -- "ts-jest:<br/>type-check, then compile" --> E["Type error fails the test"]
    S -- "ts-jest: OK" --> R
    R --> O["Pass or fail by behavior"]
    TS["tsc --noEmit"] -.-> |"checks all files, runs no tests"| T

Where types are checked depends on the transformer; tsc --noEmit is the separate, always-on check.

Setting up Vitest

Vitest needs a dev dependency and a script. A minimal setup:

Terminal
npm install --save-dev vitest
JSON
{
  "scripts": {
    "test": "vitest run",
    "test:watch": "vitest",
    "typecheck": "tsc --noEmit"
  }
}

By default Vitest looks for files named *.test.ts or *.spec.ts. A configuration file is optional; when you need one, vitest.config.ts is typed:

TypeScript
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    environment: 'node',          // or 'jsdom' for browser-like tests
    include: ['src/**/*.test.ts'],
    coverage: { provider: 'v8' },
  },
});

You import the test functions explicitly (import { describe, it, expect } from 'vitest'), or set globals: true and add "types": ["vitest/globals"] to tsconfig.json to use them without imports. Explicit imports are the safer choice, because nothing global is added to your types.

Setting up Jest with ts-jest

Jest plus ts-jest needs three packages and a preset:

Terminal
npm install --save-dev jest ts-jest @types/jest
TypeScript
// jest.config.ts
import type { Config } from 'jest';

const config: Config = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  testMatch: ['**/*.test.ts'],
};

export default config;

If you would rather avoid the global describe/it/expect types of @types/jest, install @jest/globals and import them explicitly. The result is the same API with local imports, which avoids clashes if you ever run two test frameworks in one repository.

ts-jest uses the TypeScript compiler API, so it follows your installed TypeScript version and your tsconfig.json. When you upgrade TypeScript to a new major version, check that your ts-jest version supports it before you upgrade both. A transformer that only strips types (SWC, or Vitest) does not depend on the compiler API in the same way.

Writing a typed test

A test file is regular TypeScript. The function under test is imported with its real types, so the compiler checks every call. Here is a function and its test, as they would appear in two files (shown here as one block):

TypeScript
// src/discount.ts
export type Tier = 'basic' | 'silver' | 'gold';

export function discountedPrice(price: number, tier: Tier): number {
  const rates: Record<Tier, number> = { basic: 0, silver: 0.1, gold: 0.2 };
  return Math.round(price * (1 - rates[tier]) * 100) / 100;
}

// src/discount.test.ts
import { describe, it, expect } from 'vitest';
import { discountedPrice } from './discount';

describe('discountedPrice', () => {
  it('applies no discount to the basic tier', () => {
    expect(discountedPrice(80, 'basic')).toBe(80);
  });

  it.each([
    ['silver', 72],
    ['gold', 64],
  ] as const)('applies the %s rate', (tier, expected) => {
    expect(discountedPrice(80, tier)).toBe(expected);
  });

  it('rejects unknown tiers at compile time', () => {
    // @ts-expect-error -- 'platinum' is not a Tier
    discountedPrice(80, 'platinum');
  });
});

Several typed habits are visible here. as const on the it.each table keeps the tier strings as literals, so they match Tier instead of widening to string. And @ts-expect-error records an expected compile error: tsc fails if the line ever stops being an error, which turns a type rule into a regression test. (At runtime that last test calls the function with a bad tier, so the test itself must not depend on the result.)

The matchers are typed as well. In Vitest, expect(x).toBe(y) accepts any value, because comparing different types is a legitimate way to assert "not equal". Do not expect the compiler to flag a wrong expected value; the test failing is how you find out.

The test API in action: a stand-in you can run

The real runners cannot start in the browser, but their core is small. This stand-in implements test, expect with a few matchers, and a summary, so you can run a test file's shape and see results. It is a teaching tool, not a replacement for Vitest.

TypeScript A tiny test runner with typed expect

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The first four tests pass and the last one fails on purpose, with the message expected 95, got 90. The summary line is 4 passed, 1 failed. Notice how Matchers<T> ties toBe to the type of the value you passed to expect: expect(discountedPrice(...)) is a Matchers<number>, so toBe('80') would be a compile error here. Real Vitest and Jest use a looser signature for toBe, but the structure (a generic expect returning an object of matchers) is the same.

Typing mocks and spies

A mock function records its calls so a test can check them. The risk with mocks in typed code is that a mock typed as any quietly accepts anything and stops protecting you. Both runners let you give the mock a function signature:

TypeScript
// Vitest
import { vi, expect, it } from 'vitest';

it('calls the sender with the user id', () => {
  const send = vi.fn<(userId: number, text: string) => boolean>().mockReturnValue(true);
  notify(send, 7);
  expect(send).toHaveBeenCalledWith(7, 'welcome');
  // send.mockReturnValue('yes');  // error: string is not assignable to boolean
});

// Jest (with @jest/globals)
import { jest } from '@jest/globals';
const send = jest.fn<(userId: number, text: string) => boolean>();

With the signature in place, mockReturnValue only accepts a boolean, and toHaveBeenCalledWith is checked against the parameter list. Two more helpers matter:

  • vi.spyOn(object, 'method') (Jest: jest.spyOn) wraps an existing method and keeps its types, so mockReturnValue must match the method's return type.
  • vi.mocked(fn) (Jest: jest.mocked(fn)) is a type-only cast. After vi.mock('./api') replaces a module with auto-mocks, vi.mocked(fetchUser) tells TypeScript that fetchUser is a mock, so .mockResolvedValue(...) is available, with the correct value type.

The cleanest way to avoid heavy mocking is dependency injection: pass the collaborator as a parameter whose type is a small interface. Then a test can hand in a plain object instead of patching a module. You can run this version:

TypeScript A hand-made typed mock through dependency injection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

welcome only needs something with a send method, so the fake is an ordinary object. spy keeps the argument types: send.calls is typed as an array of [to: string, _subject: string] tuples, so send.calls[0] is a known tuple and not any[]. The program prints sent: 2, calls: 3, first call: [ '[email protected]', 'Welcome!' ] and second call to: [email protected].

Testing the types themselves

Sometimes the thing you ship is a type: a utility type, a library's public API, a generic function whose return type must be precise. Ordinary runtime assertions cannot see types, so Vitest provides expectTypeOf, a compile-time assertion API:

TypeScript
import { expectTypeOf, test } from 'vitest';

test('Pick returns the chosen keys', () => {
  type User = { id: number; name: string; email: string };
  expectTypeOf<Pick<User, 'id' | 'name'>>().toEqualTypeOf<{ id: number; name: string }>();
  expectTypeOf(discountedPrice).returns.toBeNumber();
  expectTypeOf(discountedPrice).parameter(1).toEqualTypeOf<'basic' | 'silver' | 'gold'>();
});

These checks run when tsc (or vitest --typecheck) examines the file; at runtime expectTypeOf does nothing. Without Vitest you can write the same checks with the Equal helper from Recursive Types plus @ts-expect-error for things that must be rejected. Libraries such as tsd and expect-type exist for this purpose too.

What types do not replace

Types and tests guard different things:

Question Answered by
Can I call this with a string? The compiler
Does it return the right number? A test
Is the JSON from the server really shaped like my type? A runtime check (a schema validator) and a test
Did a refactor change the public types? Type tests
Does the code survive bad input? A test, because types vanish at runtime

A few habits keep a typed test suite healthy:

  • Do not weaken types to make tests easier. If you need as any in many tests, the code under test is hard to use, and the design may need a small interface (see the mailer above).
  • Test behavior, not implementation. Assert what a function returns or what a collaborator received, not how the function is built inside.
  • Include *.test.ts in type checking. Make sure your tsconfig.json covers test files, or errors in them will go unnoticed when the runner strips types.
  • Keep fixtures typed. Use factory functions that return full objects (makeUser({ name: 'Ada' })), so adding a required field to the type produces one compile error in the factory instead of dozens in tests.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A Vitest test file contains a type error on one line. What happens when you run vitest?

    Vitest strips types without checking them. Use tsc --noEmit (or vitest --typecheck) to find type errors.
  2. 2. What does ts-jest do that a type-stripping transformer does not?

    ts-jest compiles with the TypeScript compiler, so type errors can fail the test run. SWC and Babel only remove the types.
  3. 3. Why give a mock a signature, as in vi.fn<(id: number) => string>()?

    An untyped mock accepts anything. A signature keeps return values and expected arguments type-safe.
  4. 4. What is the purpose of a @ts-expect-error line in a test?

    Unlike @ts-ignore, @ts-expect-error complains when no error exists, which makes it a way to test that invalid code stays rejected.
  5. 5. Which design makes a function easiest to test without module-level mocking?

    Dependency injection with a narrow interface lets a test pass a plain fake object, and the compiler still checks it matches.

Summary

  • Test runners run JavaScript, so something must strip the types first. Vitest and SWC strip without checking; ts-jest checks. Run tsc --noEmit as well.
  • Vitest needs a single dev dependency and *.test.ts files. Jest needs ts-jest (or another transformer) and @types/jest or @jest/globals.
  • Use as const tables for it.each and @ts-expect-error to lock in compile-time rules.
  • Give mocks a function signature (vi.fn<...>(), jest.fn<...>()) and use vi.mocked / jest.mocked to type module mocks.
  • Prefer dependency injection with small interfaces so tests pass plain typed fakes instead of patching modules.
  • Test types with expectTypeOf or an Equal helper when the type is the product, and keep runtime validation and tests for what types cannot see.

Next: Project: Typed To-Do CLI