Testing a TypeScript application well means checking both what the program does at runtime and whether its types prevent invalid code before it runs. This guide provides a reusable checklist for choosing test boundaries, configuring a runner, testing asynchronous and external code, writing type-level checks, interpreting coverage, and preparing a reliable release.
Overview
A TypeScript test suite is not automatically type-safe just because the application is written in TypeScript. Many test runners transform or execute test files through their own pipeline, while the TypeScript compiler performs separate static analysis. A green test run can therefore coexist with type errors unless compilation or a dedicated type-checking step also runs in development and CI.
Start by separating four responsibilities:
- Unit tests: verify a small function, class, hook, or service with controlled inputs.
- Integration tests: verify that real modules work together, such as a service and database adapter or an API route and validation layer.
- Type-level tests: verify that types accept valid usage and reject invalid usage at compile time.
- End-to-end tests: verify a user or system workflow through deployed or near-production boundaries.
Use the smallest boundary that gives useful confidence. A pure price calculation usually needs a unit test, not a database-backed integration test. Conversely, testing a repository with a hand-written mock may prove little if the real issue is an incorrect query, transaction, or serialization boundary.
Choose a runner based on the project rather than habit. Vitest is often convenient for projects already using a modern module and build toolchain. Jest has a mature ecosystem and familiar mocking model. A native Node.js test runner can reduce dependencies for server-side packages, but may require you to assemble more of the transformation, coverage, and mocking workflow yourself. Check the current documentation for your selected runner before copying configuration, especially when using ESM, path aliases, JSX, or decorators.
| Runner | Useful fit | Double-check |
|---|---|---|
| Vitest | TypeScript applications sharing a modern bundler-oriented workflow | Module mode, aliases, environment setup, and mocking behavior |
| Jest | Teams that value its established ecosystem and configurable test model | Transformers, ESM support, path mapping, and differences between runtime and compiler settings |
| Native Node.js runner | Small or server-focused projects seeking a lean dependency surface | TypeScript execution strategy, coverage tooling, and replacement or isolation of modules |
Checklist by scenario
For a new unit test
- Identify the behavior and write a test name that describes the observable result.
- Keep setup close to the test unless a shared fixture genuinely improves clarity.
- Test boundary values, invalid inputs, and important branches rather than repeating ordinary examples.
- Prefer public behavior over private implementation details, so refactoring does not require rewriting the suite.
- Let TypeScript infer local values where that improves readability, but annotate test data when the annotation documents an important contract.
For asynchronous code
- Return or await the promise in every asynchronous test. A test that forgets to await can pass before the assertion runs.
- Test rejected promises with the runner's asynchronous assertion pattern rather than wrapping an assertion in an unobserved callback.
- Control time, retries, randomness, and network access explicitly. Restore fake timers, spies, and environment variables after each test.
- Include a timeout or cancellation case when the production code has one.
For API clients and runtime data
TypeScript types do not validate JSON received from an HTTP request. Test the boundary where untrusted data enters the application. A useful pattern is to parse the response with a runtime schema, map it to an internal type, and test both a valid payload and malformed or incomplete payloads.
- Test status handling, unexpected content, missing fields, and error response shapes.
- Mock the transport at the boundary when testing application logic, but use an integration test for the real request-to-parser path.
- Keep request and response fixtures small, named, and representative of actual contracts.
For database adapters
- Unit-test mapping and business rules without a database.
- Integration-test queries, migrations, constraints, transactions, and serialization against a controlled database environment.
- Verify cleanup between tests. Shared state makes failures order-dependent and difficult to reproduce.
- Test the failure modes your application handles, such as a missing record, duplicate key, or unavailable connection.
For module mocking
Mock dependencies when isolation is the purpose, not merely because mocking is available. A mock should preserve the shape of the dependency closely enough that the test remains meaningful. Type-safe mock helpers can catch renamed methods or incompatible return values, but they cannot prove that the mock behaves like the real service.
Document whether a mock is a fixed response, a spy for interaction assertions, or a simulated failure. Reset call history and implementation between tests, and restore replaced modules after the suite. ESM and CommonJS projects can expose different mocking rules, so follow the runner's module-specific API instead of assuming that one syntax works everywhere.
For type-level tests
Use type-level checks for public utilities, generic functions, discriminated unions, branded values, and library declarations. Check that valid calls infer the expected type and that deliberately invalid calls produce an error. Keep invalid examples isolated so they do not prevent the rest of the project from compiling.
Runtime tests and type-level tests answer different questions: runtime tests ask whether JavaScript behavior is correct; type-level tests ask whether the compiler sees the intended contract. Run both. A compiler pass does not replace a test for malformed runtime data, and a runtime pass does not prove that consumers receive useful types.
What to double-check
Before relying on the suite, inspect the boundary between TypeScript, the test runner, and the module system.
- Compiler configuration: Decide whether CI runs
tsc --noEmitseparately from tests. Ensure the test files are included in the intended configuration, or use a clearly documented test-specific configuration. - Path aliases: An alias in
tsconfig.jsonmay not be understood by the runner, coverage tool, or production bundler. Configure each layer deliberately and test an aliased import in CI. - ESM and CommonJS: Confirm package mode, file extensions, export syntax, and transformation settings. Do not assume that a configuration copied from a CommonJS project will work in an ESM project.
- Environment: Select the correct environment for browser APIs, server APIs, or a plain Node.js process. Avoid global browser-like objects in server tests unless they are intentionally provided.
- Coverage scope: Exclude generated files and deliberate infrastructure where appropriate, but do not use exclusions to hide untested production paths. Review branch coverage for decision-heavy code.
- Test isolation: Check for shared mutable objects, leaked environment variables, open handles, persistent timers, and test order dependencies.
- Fixtures: Make fixture intent visible. A fixture that contains irrelevant fields can conceal which contract the test actually depends on.
Coverage is a signal for investigation, not a quality score by itself. High line coverage can miss incorrect assertions, untested error paths, and realistic integration failures. Review whether each assertion would fail if the behavior regressed.
Common mistakes
- Testing only the happy path. Add cases for invalid input, empty results, rejected dependencies, and boundary values.
- Using broad casts in test setup.
as anycan make an invalid fixture compile while hiding a changed contract. Prefer builders with sensible defaults and explicit overrides. - Mocking every dependency. Excessive mocks produce tests that describe an imagined system. Keep a smaller set of integration tests around important adapters and workflows.
- Confusing compilation with execution. A passing transform may skip type checking. Make the compiler check an explicit command in local development or CI.
- Asserting implementation details. Tests that inspect private calls, exact internal ordering, or incidental object structure become expensive during harmless refactors.
- Ignoring cleanup. A test that passes alone but fails after another test often indicates leaked state, timers, mocks, or database data.
- Copying outdated runner syntax. Mocking APIs, ESM behavior, configuration formats, and Node.js support can change across major releases. Verify examples against the versions installed in the project.
For a broader project setup, connect the test commands to the same configuration and CI plan used for linting and builds. The complete TypeScript project template is a useful companion, while the guide to testing TypeScript code provides related guidance on mocks and coverage.
When to revisit
Revisit this checklist whenever the inputs to your testing workflow change. The most useful review points are:
- when changing from JavaScript to TypeScript or tightening compiler settings;
- when replacing Jest, Vitest, or a native runner;
- when changing ESM or CommonJS mode, package exports, bundling, or path aliases;
- when adding a database, external API, queue, browser environment, or runtime validator;
- when a feature introduces concurrency, retries, time-based behavior, or significant caching;
- before a release, after a dependency upgrade, and during periodic planning or coverage reviews.
Use this release-readiness checklist as the final pass:
- Run the compiler with the intended production and test configurations.
- Run unit, integration, type-level, and end-to-end checks that apply to the changed area.
- Verify asynchronous failures are awaited and no open handles or leaked state remain.
- Review changed branches and error paths rather than chasing a universal coverage percentage.
- Confirm aliases, module mode, environment setup, fixtures, and mocks behave in CI as they do locally.
- Record intentional gaps and create follow-up work instead of masking them with exclusions or broad casts.
Type-safe testing is a workflow, not a single library choice. Keep runtime behavior, compile-time contracts, and integration boundaries visible in the suite, then repeat the checklist whenever the application or its tooling changes.