TypeScript Testing Patterns: Mocks, Async Code, and Type-Safe Fixtures with Vitest and Jest
testingvitestjestmockingfixtures

TypeScript Testing Patterns: Mocks, Async Code, and Type-Safe Fixtures with Vitest and Jest

TTypeScript Toolbox Editorial Team
2026-11-29
9 min read

Compare Vitest and Jest while learning type-safe patterns for mocks, async assertions, spies, fixtures, and rejected promises in TypeScript.

TypeScript tests are easiest to maintain when the types describe the same boundaries as the production code. This guide compares Vitest and Jest, then shows practical patterns for typed mocks, spies, asynchronous behavior, rejected promises, and reusable fixtures without turning every test into a collection of unsafe casts.

Overview

TypeScript testing has two separate concerns: the test must satisfy the compiler, and the test must accurately exercise runtime behavior. A mock can be perfectly valid to TypeScript while returning the wrong data shape. Conversely, a test can behave correctly at runtime but use as any so broadly that refactoring no longer exposes broken assumptions.

Vitest and Jest provide similar building blocks: a test function, assertions, mocks, spies, fake timers, and lifecycle hooks. Their APIs are not interchangeable, however. Vitest uses the vi namespace for mocking utilities, while Jest uses jest. Matcher names and common test structure are often familiar across both tools, but helper types, module mocking behavior, configuration, and transform support should be checked against the version used by your project.

The durable pattern is to keep application types independent from the test runner. Define the service contract, create a small fixture factory, and mock only the dependency at the boundary being tested. This approach works for a Node.js service, a React application, a Next.js route handler, or a typed API client.

For broader context, pair these patterns with the guide to testing TypeScript applications and the TypeScript utility types cheat sheet.

How to compare options

Choose a test runner by comparing the behavior that matters to your repository, not by treating one set of helper names as universally superior. Before migrating or starting a project, review these areas:

  • Project integration: Confirm how the runner works with your module format, build tool, JSX configuration, path aliases, and test environment.
  • Mocking model: Determine whether your tests need function mocks, spies, module mocks, replaced properties, or controlled timers. Module mocking is especially important when code imports a dependency at module scope.
  • Type ergonomics: Check whether the runner’s mock helper types preserve argument and return types well enough for your team. A convenient runtime API does not automatically provide precise TypeScript inference.
  • Async diagnostics: Verify how clearly failed promise assertions identify the actual error, missing await, or accidentally unresolved promise.
  • Maintenance cost: Consider the number of custom helpers, setup files, transforms, and compatibility workarounds required by the existing codebase.
ConcernVitestJestComparison question
Test and assertion structureUses familiar describe, it/test, and expect patterns.Uses familiar describe, it/test, and expect patterns.Can the team share conventions and fixtures?
Mock namespaceMocking helpers are exposed through vi.Mocking helpers are exposed through jest.Are imports and helper types consistent with the selected runner?
Typed mocksUse the runner’s mock types or explicit function contracts.Use Jest’s mock types or explicit function contracts.Will a refactor reveal stale mock behavior?
Module mockingRequires runner-specific module mock setup and import behavior.Requires Jest-specific module mock setup and import behavior.Are mocks declared in the correct order and scope?
ConfigurationReview the project’s build, environment, and alias configuration.Review the project’s transform, environment, and alias configuration.Does the test runner resolve files as production does?

This table describes decision areas rather than a permanent feature ranking. Both tools evolve, and configuration support can depend on the surrounding framework. Recheck the official documentation and your installed version before copying a configuration from an older project.

Feature-by-feature breakdown

1. Type the dependency contract first

A mock is much easier to type when the production dependency has a narrow interface. Avoid mocking a large client object if the unit under test only needs one method.

export type User = {
  id: string;
  email: string;
  active: boolean;
};

export interface UserRepository {
  findById(id: string): Promise<User | null>;
}

export async function loadActiveUser(
  repository: UserRepository,
  id: string,
): Promise<User> {
  const user = await repository.findById(id);

  if (!user || !user.active) {
    throw new Error('Active user not found');
  }

  return user;
}

The return type makes the success and failure paths explicit. It also gives the test compiler useful information without requiring a runner-specific type assertion.

2. Build fixtures with factories, not shared mutable objects

A fixture factory creates a fresh value for each test and permits focused overrides. This prevents one test from silently changing the data seen by another.

export function makeUser(
  overrides: Partial<User> = {},
): User {
  return {
    id: 'user-1',
    email: 'person@example.test',
    active: true,
    ...overrides,
  };
}

const inactiveUser = makeUser({ active: false });
const customUser = makeUser({ id: 'user-2' });

Partial<User> is appropriate for fixture overrides because the factory supplies defaults. It should not be used to pretend that a partial API response is a complete User. If external data is untrusted, validate it at runtime before converting it to the application type.

3. Mock functions without losing their contract

The most portable pattern is to define a function with the same parameter and return types as the dependency. The exact mock factory differs between runners, but the contract remains understandable.

type FindById = UserRepository['findById'];

// Vitest
import { vi } from 'vitest';
const findById = vi.fn<FindById>();

// Jest
import { jest } from '@jest/globals';
const findById = jest.fn<FindById>();

const repository: UserRepository = { findById };

findById.mockResolvedValue(makeUser());

Generic signatures and helper types vary between runner versions, so treat this as a pattern to adapt to the installed API. If the generic form is not accepted by your version, create an explicitly typed function and wrap or spy on it instead of immediately falling back to any.

4. Test asynchronous success and failure explicitly

Always return or await the promise produced by the assertion. Without await, a test may finish before the rejection assertion runs, creating a misleading result.

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

it('returns an active user', async () => {
  const repository: UserRepository = {
    findById: vi.fn().mockResolvedValue(makeUser()),
  };

  await expect(loadActiveUser(repository, 'user-1'))
    .resolves.toEqual(makeUser());
});

it('rejects an inactive user', async () => {
  const repository: UserRepository = {
    findById: vi.fn().mockResolvedValue(makeUser({ active: false })),
  };

  await expect(loadActiveUser(repository, 'user-1'))
    .rejects.toThrow('Active user not found');
});

In Jest, use the equivalent Jest imports and mock factory. The important behavior is the same: configure the promise returned by the dependency, then await the resolves or rejects assertion. You can also write a try/catch assertion when you need to inspect several properties of a custom error, but make sure the test fails if no error is thrown.

5. Use spies to verify collaboration, not implementation trivia

A spy is useful when the real implementation should run but the test must verify an observable interaction, such as a logger call or an adapter invocation. Prefer checking meaningful arguments and call counts over asserting every internal step.

const repository: UserRepository = {
  findById: vi.fn().mockResolvedValue(makeUser()),
};

await loadActiveUser(repository, 'user-1');

expect(repository.findById).toHaveBeenCalledWith('user-1');

If TypeScript does not recognize mock matchers on the property, keep the mock in a named variable with an explicit function type. That usually gives both the production object and the test assertions a clearer type than repeatedly casting the whole repository.

6. Separate fixture types from transport types

API fixtures often include fields that differ from domain objects: serialized dates, nullable values, status strings, or error envelopes. Keep those shapes separate. A test that passes a domain object directly where the application expects JSON can skip the conversion logic you intended to test.

This is also where runtime validation belongs. TypeScript types disappear at runtime, so a mocked response does not prove that production data is valid. For API boundaries, combine static API typing with a runtime schema or explicit decoder, and test both valid and malformed inputs.

7. Keep module mocks close to the boundary

Module mocks can be useful for network clients, environment-dependent libraries, and platform APIs. They can also become brittle when imports, module formats, or runner configuration change. Prefer dependency injection for business-critical collaborators when practical. If a module mock is necessary, keep its setup in the test or a clearly named setup file, reset it between tests, and document whether the mock replaces the whole module or only one export.

Best fit by scenario

  • Choose Vitest when: the project already uses a compatible modern build workflow and you want test, mock, and assertion utilities that fit that toolchain. Confirm path aliases, environment setup, and module mocking behavior before standardizing the repository.
  • Choose Jest when: the codebase already has established Jest configuration, setup files, custom matchers, or shared testing conventions. Preserving a mature test ecosystem can be more valuable than changing runners for a small API difference.
  • Use explicit function contracts when: runner-specific mock types become difficult to understand or your team shares test helpers across tools. A typed adapter can be clearer than a deeply nested generic.
  • Use fixture factories when: many tests repeat the same object shape with small variations. Keep defaults realistic, use Partial<T> only for overrides, and return a fresh object on every call.
  • Use integration tests instead of extensive mocks when: the important behavior depends on serialization, routing, persistence, or a real adapter boundary. Unit mocks should not become a substitute for testing those boundaries.

For recurring compiler problems in test helpers, consult the common TypeScript errors diagnostic guide and the compiler errors reference. If aliases work in the editor but fail in tests, the path aliases guide covers the separate resolution layers to inspect.

When to revisit

Revisit this guide whenever Vitest or Jest changes major behavior, your TypeScript version changes, or the project changes its module system, bundler, JSX mode, or runtime environment. A new test dependency can alter transform and alias configuration even when the test source looks unchanged.

Use this short review workflow when a mock becomes stale or a new service fixture is introduced:

  1. Read the production contract: Compare the mock’s parameters, return type, optional fields, and error behavior with the current interface.
  2. Run the compiler separately: Use the project’s normal type-check command. A passing test run does not necessarily mean test files are being checked with the intended TypeScript settings.
  3. Inspect the async boundary: Look for missing await, a promise returned from the wrong mock method, or a test that can finish without reaching its assertion.
  4. Check fixture ownership: Ensure each test receives a fresh object and that overrides do not mutate a shared default.
  5. Verify runtime data: If the fixture represents an API response, confirm its serialized shape and validation path rather than passing an already-normalized domain object.
  6. Review runner configuration: Check aliases, environment selection, setup files, module mocks, and matcher extensions against the installed runner version.

Finally, remove a mock when it no longer isolates a meaningful boundary. Strong TypeScript testing is not about making every test maximally typed or heavily mocked. It is about making the contract, data shape, asynchronous outcome, and failure mode visible enough that a production refactor produces a useful test failure. Recheck the runner documentation when dependencies change, but keep the core patterns—narrow interfaces, fresh fixtures, explicit promises, and minimal casts—stable.

Related Topics

#testing#vitest#jest#mocking#fixtures
T

TypeScript Toolbox Editorial Team

Developer Education 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.