GGistDev

Testing in TypeScript

Test TypeScript with Jest or Vitest; keep types in sync and fast builds.

Vitest (recommended for Vite/esbuild)

// vitest.config.ts
import { defineConfig } from "vitest/config";
export default defineConfig({
  test: { environment: "node" }
});

Run with vitest. TS is compiled via esbuild under the hood.

Jest with ts-jest

// jest.config.ts
import type { Config } from "jest";
const config: Config = {
  preset: "ts-jest",
  testEnvironment: "node",
};
export default config;

Assertions and helpers

  • Built-in expect (Jest/Vitest)
  • Add @testing-library/* for DOM/React
  • Use as const in fixtures for narrow literal types

Type-only tests

Use tsd or expectTypeOf (Vitest) to assert types.

import { expectTypeOf } from "vitest";
expectTypeOf<string>("hi");

Mocks and fakes

Prefer dependency injection and small interfaces; avoid deep jest.spyOn trees.

Example

import { describe, it, expect } from "vitest";
function add(a: number, b: number) { return a + b }

describe("add", () => {
  it("adds numbers", () => {
    expect(add(2, 2)).toBe(4);
  });
});

Summary

  • Use Vitest or Jest with appropriate transformers
  • Assert runtime behavior and, when useful, types
  • Favor small units with simple fakes over complex mocks