Testing TypeScript Code: Types, Mocks, Coverage, and Reliable Test Workflows
testingVitestJestmockingtest coverageCI

Testing TypeScript Code: Types, Mocks, Coverage, and Reliable Test Workflows

TTypeScript Website Editorial Team
2026-11-07
7 min read

A practical TypeScript testing checklist covering Vitest, Jest, mocks, coverage, type tests, tsconfig, and CI workflows.

Testing TypeScript well requires more than running functions and checking coverage percentages. This guide gives you a reusable workflow for unit, integration, and type-level tests, with practical Vitest and Jest patterns, separate TypeScript configuration, safer mocks, error assertions, and a CI checklist for catching both runtime and typing regressions.

Overview

TypeScript protects your code during development, but its types are generally removed before JavaScript runs. A test suite therefore needs to check two different contracts: what the program does at runtime and what the compiler accepts at development time. Testing only one of these leaves a gap.

Runtime tests execute code and verify observable behavior. They are appropriate for functions, components, API handlers, database adapters, and workflows. Type tests intentionally ask the compiler whether an API accepts or rejects particular code. They are useful for exported utilities, generic functions, discriminated unions, component props, and public library interfaces.

Test typeWhat it catchesTypical toolsWhen to use it
Unit or runtime testIncorrect values, branches, exceptions, and side effectsVitest or Jest with an assertion libraryPure functions and isolated modules
Integration testIncorrect boundaries between modules, services, or adaptersVitest or Jest with controlled dependenciesAPI routes, persistence, queues, and application workflows
Component testIncorrect rendering, interaction, and user-visible statesA runner plus a UI testing libraryReact and other frontend components
Type testBroken inference, invalid assignments, and accidental API changesTypeScript compiler or a type-testing utilityReusable libraries and complex public types

A sensible default is to use one test runner consistently across a project, then add type-level checks where the compiler itself is part of the product contract. Vitest and Jest can both work well with TypeScript; the important decisions are consistent module handling, isolated test configuration, reliable mocks, and a CI command that actually fails when types break.

Checklist by scenario

For a new TypeScript project

  • Enable strict compiler checking in the application or library configuration unless a documented migration constraint prevents it.
  • Choose Vitest or Jest according to the project’s module system, framework integrations, and existing team knowledge.
  • Keep test files discoverable with a predictable convention such as *.test.ts, *.spec.ts, and their component equivalents.
  • Define separate test and build configurations when test globals, DOM libraries, path aliases, or module settings differ from production code.
  • Add one representative test for a successful result, one meaningful edge case, and one expected failure before expanding coverage.

For unit testing a function

Start with the function’s observable contract rather than its implementation. For a parser, test valid input, malformed input, and boundary values. For a formatter, test stable output and the inputs that previously caused regressions. Avoid asserting private variables or incidental call order unless that behavior is part of the contract.

import { describe, expect, it } from "vitest";
import { parsePort } from "./parsePort";

describe("parsePort", () => {
  it("returns a valid numeric port", () => {
    expect(parsePort("3000")).toBe(3000);
  });

  it("rejects an invalid port", () => {
    expect(() => parsePort("abc")).toThrow(/port/i);
  });
});

The same structure works with Jest after replacing the runner-specific imports and configuration. For asynchronous code, await the promise in the test and assert the rejection explicitly; do not allow an unawaited promise to make a test pass accidentally.

For integration and API tests

  • Keep network, file-system, database, and clock boundaries explicit.
  • Use a test database, in-memory adapter, or narrowly scoped fake rather than silently connecting to a developer environment.
  • Validate both the response or return value and important side effects, such as a saved record or emitted event.
  • Include malformed external data when the application uses runtime validation. TypeScript annotations alone cannot verify JSON received over a network.

For API boundaries, pair static API typing with runtime schemas where untrusted data enters the system. A schema library such as Zod can make the boundary explicit, while the test suite verifies that valid and invalid payloads are handled as intended. See the guides on TypeScript runtime validation and Zod schemas for APIs and JSON for patterns that complement runtime tests.

For mocking modules, timers, and external services

  • Mock only a boundary your test does not intend to exercise, such as an email provider, payment gateway, or system clock.
  • Type mock return values so a refactor cannot make the mock disagree with the real function silently.
  • Restore or reset mocks after each test when shared state could affect later cases.
  • When using fake timers, advance the clock deliberately and restore real timers in cleanup.
  • Test the behavior caused by a dependency failure, not just that a mock was called.

Mocking APIs differ between Vitest and Jest, particularly around ESM, hoisting, and module restoration. Check the runner’s version-specific documentation when changing module formats, and keep a small working example in the repository so upgrades can be evaluated against real project behavior.

For type-level tests

A runtime assertion cannot prove that a generic preserves a type or that an invalid prop is rejected. Add compile-time assertions for public types and difficult inference behavior. A simple approach is to keep an *.type-test.ts file that is included in a dedicated TypeScript check. If the project uses a type-testing utility, prefer its documented assertions and mark intentionally invalid examples clearly.

// type-test.ts
import { expectTypeOf } from "expect-type";
import { makeResult } from "./result";

const result = makeResult("ok");
expectTypeOf(result).toEqualTypeOf<{ ok: true; value: string }>();

Negative cases need special care. Use an expected-error directive only when the line should fail, and ensure your compiler configuration reports an unused directive. Otherwise, a test can continue passing after the invalid code becomes valid for an unintended reason.

What to double-check

Separate configuration from production compilation

Do not assume the test runner’s transpilation is the same as the project’s real TypeScript build. A runner may transform TypeScript without performing full type checking. Keep a production-oriented tsconfig.json and, if needed, a tsconfig.test.json that adds test files and globals without weakening the application’s strictness.

// package.json scripts
{
  "scripts": {
    "test": "vitest run",
    "test:watch": "vitest",
    "typecheck": "tsc --noEmit -p tsconfig.json",
    "typecheck:test": "tsc --noEmit -p tsconfig.test.json",
    "coverage": "vitest run --coverage"
  }
}

For Jest, the same separation applies even if a transformer handles TypeScript during test execution. Run the compiler independently unless your chosen toolchain clearly performs an equivalent full check.

Coverage boundaries and quality

Coverage is a diagnostic, not a substitute for test design. Exclude generated files, declaration files, build output, and configuration that cannot provide meaningful behavior evidence. Do not exclude difficult business logic merely to improve a percentage. Review uncovered branches and ask whether they represent an untested requirement, unreachable code, or a design that should be simplified.

Module format, aliases, and environment

When tests fail only in CI or only after switching to ESM, inspect the relationship between TypeScript’s module setting, the runner configuration, package exports, and path aliases. An alias that works for the compiler may not work at runtime unless the bundler or test runner understands it too. The TypeScript path alias guide is a useful companion when diagnosing this boundary.

Common mistakes

  • Confusing compilation with behavior: A clean type check does not prove that a function returns the right value or handles a rejected promise.
  • Confusing transpilation with type checking: A fast test transform may remove types but never report a type regression. Keep a separate compiler command.
  • Over-mocking: If every dependency is replaced with a mock, integration errors can remain invisible. Test important boundaries with realistic adapters as well.
  • Testing implementation details: Assertions tied to private calls make refactoring expensive and often fail without a user-visible regression.
  • Ignoring rejected promises: Always return or await asynchronous assertions, especially for expected errors.
  • Sharing mutable fixtures: Create fresh input data for each test or reset it in setup and teardown.
  • Using snapshots for everything: Snapshots can document stable output, but they should not replace focused assertions about important behavior.
  • Trusting coverage thresholds blindly: A high number can coexist with weak assertions, duplicated tests, or untested failure paths.

When to revisit

Revisit this testing workflow before a seasonal planning cycle, when the team changes its runner, or when a framework, bundler, or module format changes. Configuration that worked for CommonJS may require review after an ESM migration; the same is true when adding React, Next.js, server-side code, or browser APIs to a previously Node-focused project. The tsconfig guide can help separate compiler concerns before changing test settings.

Use this short checklist during a stack upgrade or regression investigation:

  1. Run runtime tests against a clean install and confirm the intended environment is being used.
  2. Run production and test type checks separately with the expected tsconfig files.
  3. Exercise at least one success, boundary, and failure path for each changed behavior.
  4. Review mocks, fake timers, fixtures, and cleanup for state that can leak between tests.
  5. Inspect coverage changes by branch and requirement, not only by total percentage.
  6. Confirm CI tests the same module resolution, environment variables, and build artifacts used in deployment.
  7. Add a regression test before closing an incident, including a type test when the failure involved inference or a public API.

A reliable TypeScript test workflow is therefore layered: runtime tests protect behavior, integration tests protect boundaries, type tests protect the compiler-facing API, and CI runs each layer explicitly. Keep those responsibilities visible, and the suite remains useful as the project and its tools evolve.

Related Topics

#testing#Vitest#Jest#mocking#test coverage#CI
T

TypeScript Website Editorial Team

Technical Editors

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.