TypeScript Strict Mode in Tests: Catch Runtime Bugs at Compile Time
Most TypeScript projects enable strict mode in production code but loosen it for tests. That's backwards — tests are where you discover bugs, and strict mode finds them earlier. This guide covers enabling strict mode in your test tsconfig, the specific checks that matter most, patterns for writing strict tests without drowning in type assertions, and how to handle the edge cases that make teams give up on strict tests.
Key Takeaways
Use a separate tsconfig.test.json that extends production config. Don't relax strict settings in your main tsconfig — set them tighter in tests.
strictNullChecks is the most valuable strict check for tests. It forces you to handle undefined returns from lookups explicitly, which catches the most common class of runtime errors.
noUncheckedIndexedAccess is even stricter — and worth it. Array indexing returns T | undefined, forcing you to check before using. Most bugs live in index 0 assumptions.
Use assertion functions instead of non-null assertions. expect(value).toBeDefined() narrows types in Vitest. In Jest, write a typed assertDefined<T>() helper.
Don't disable strict mode to make a test compile. If a strict error surfaces in your test, it's pointing at a real problem in your production code's types.
The Backwards Pattern
Teams typically write tsconfig like this:
// tsconfig.json
{
"compilerOptions": {
"strict": true
}
}
// tsconfig.test.json
{
"extends": "./tsconfig.json",
"compilerOptions": {
"strict": false,
"noImplicitAny": false
}
}The motivation is understandable: strict tests are harder to write, especially with mocking libraries that rely on partial types. But this pattern defeats the purpose of TypeScript in tests. The type errors that strict mode catches in tests are the same ones that cause production bugs — they don't disappear, they just become runtime errors.
The better pattern: keep strict mode in tests, learn the patterns that make it work.
Setting Up Strict Test Config
Create a tsconfig.test.json that extends your production config and adds test-specific settings without loosening strictness:
{
"extends": "./tsconfig.json",
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"types": ["jest", "node"],
"esModuleInterop": true,
"resolveJsonModule": true
},
"include": [
"src/**/*.test.ts",
"src/**/*.spec.ts",
"tests/**/*.ts"
]
}Point Jest at this config:
// jest.config.ts
import type { Config } from 'jest';
const config: Config = {
preset: 'ts-jest',
tsconfig: 'tsconfig.test.json',
testEnvironment: 'node',
};
export default config;For Vitest:
// vitest.config.ts
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
typecheck: {
tsconfig: './tsconfig.test.json',
},
},
});strictNullChecks: The Most Important Flag
With strictNullChecks, the TypeScript compiler knows that functions can return undefined and forces you to handle it. This matters enormously in tests.
Consider this without strict null checks:
const user = users.find((u) => u.id === '123');
expect(user.name).toBe('Alice'); // Compiles fine, throws at runtime if not foundWith strictNullChecks:
const user = users.find((u) => u.id === '123');
// Error: Object is possibly 'undefined'.
expect(user.name).toBe('Alice');The error tells you your test isn't handling the case where the user doesn't exist. The fix reveals a real gap:
const user = users.find((u) => u.id === '123');
expect(user).toBeDefined();
// In Vitest, expect(user).toBeDefined() narrows the type
if (!user) return; // Still needed in Jest
expect(user.name).toBe('Alice');Or with an assertion function (see below).
noUncheckedIndexedAccess: Tighter Array Safety
This flag makes array indexing return T | undefined instead of T:
const items = ['a', 'b', 'c'];
const first = items[0]; // Type: string | undefined (not string)
// Without noUncheckedIndexedAccess:
expect(first.toUpperCase()).toBe('A'); // Compiles
// With noUncheckedIndexedAccess:
// Error: Object is possibly 'undefined'.
expect(first.toUpperCase()).toBe('A');This catches the #1 source of Cannot read properties of undefined errors. The fix is explicit:
const items = ['a', 'b', 'c'];
const first = items[0];
expect(first).toBeDefined();
expect(first!.toUpperCase()).toBe('A'); // Non-null assertion after explicit checkOr better, use an assertion function that narrows the type (see next section).
Assertion Functions That Narrow Types
Jest's expect(value).toBeDefined() doesn't narrow the type in TypeScript — after the assertion, the value is still T | undefined. You need an explicit type guard or assertion function.
Write a typed assertion helper:
// tests/helpers/assert.ts
export function assertDefined<T>(
value: T | undefined | null,
message?: string
): asserts value is T {
if (value === undefined || value === null) {
throw new Error(message ?? `Expected value to be defined, got ${value}`);
}
}
export function assertType<T>(
value: unknown,
guard: (v: unknown) => v is T,
message?: string
): asserts value is T {
if (!guard(value)) {
throw new Error(message ?? `Type assertion failed`);
}
}Now the type narrows after the assertion:
import { assertDefined } from './helpers/assert';
const user = users.find((u) => u.id === '123');
assertDefined(user, 'User 123 should exist in test fixtures');
// TypeScript now knows user is User, not User | undefined
expect(user.name).toBe('Alice');
expect(user.email).toMatch(/@example\.com$/);In Vitest, expect(value).toBeDefined() does narrow the type in recent versions — check your version.
Typing Mocked Functions
Mock libraries return partial or any-typed objects that break strict mode. The fix is explicit typing at the mock boundary.
For jest.fn():
// Without strict typing:
const mockFn = jest.fn();
mockFn.mockReturnValue(42); // No type checking on return value
// With strict typing:
const mockFn = jest.fn<number, [string, boolean]>();
mockFn.mockReturnValue(42); // OK
mockFn.mockReturnValue('oops'); // Error: Argument of type 'string' is not assignable to parameter of type 'number'For module mocks, use typed overrides:
import type { UserService } from '../services/UserService';
const mockUserService: jest.MockedObject<UserService> = {
findById: jest.fn(),
create: jest.fn(),
update: jest.fn(),
delete: jest.fn(),
};
// All methods are typed mocks — you get autocomplete and type checking
mockUserService.findById.mockResolvedValue({
id: '123',
name: 'Alice',
email: 'alice@example.com',
createdAt: new Date().toISOString(),
});jest.MockedObject<T> converts all methods of T to jest.Mock variants while preserving the original types.
Handling exactOptionalPropertyTypes
With exactOptionalPropertyTypes, setting an optional property to undefined explicitly is different from omitting it:
interface UserUpdate {
name?: string;
email?: string;
}
// Without exactOptionalPropertyTypes — both compile:
const update1: UserUpdate = { name: undefined }; // OK
const update2: UserUpdate = { name: 'Alice' }; // OK
// With exactOptionalPropertyTypes:
const update1: UserUpdate = { name: undefined }; // Error: Type 'undefined' is not assignable to type 'string'
const update2: UserUpdate = { name: 'Alice' }; // OK
const update3: UserUpdate = {}; // OK (omitted)In tests, this means you can't set optional fields to undefined as a way to "clear" them. Use Partial<T> for test fixtures that intentionally leave fields unset:
function buildUser(overrides: Partial<User> = {}): User {
return {
id: 'test-id',
name: 'Test User',
email: 'test@example.com',
createdAt: new Date().toISOString(),
...overrides,
};
}Strict Fixtures Without the Pain
Strict mode makes fixture building verbose if done naively. Use a builder pattern with typed defaults:
// tests/fixtures/UserFixture.ts
import type { User, Address, Role } from '../../src/types';
class UserBuilder {
private user: User = {
id: `user-${Math.random().toString(36).slice(2)}`,
email: 'test@example.com',
name: 'Test User',
role: 'viewer',
address: null,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
};
withId(id: string): this {
this.user = { ...this.user, id };
return this;
}
withEmail(email: string): this {
this.user = { ...this.user, email };
return this;
}
withRole(role: Role): this {
this.user = { ...this.user, role };
return this;
}
withAddress(address: Address): this {
this.user = { ...this.user, address };
return this;
}
build(): User {
return this.user;
}
}
export const aUser = () => new UserBuilder();Usage:
const adminUser = aUser().withRole('admin').withEmail('admin@example.com').build();
const regularUser = aUser().build();Every method is typed — withRole('invalid') won't compile, and build() always returns a complete User, not Partial<User>.
Testing Type-Level Behavior
Sometimes you want to assert that TypeScript correctly rejects invalid inputs. Vitest has built-in type testing support:
// tests/types.test-d.ts
import { expectTypeOf, test } from 'vitest';
import type { ParsedConfig } from '../../src/config';
test('ParsedConfig has required fields', () => {
expectTypeOf<ParsedConfig>().toHaveProperty('apiUrl');
expectTypeOf<ParsedConfig>().toHaveProperty('timeout');
expectTypeOf<ParsedConfig['timeout']>().toBeNumber();
});
test('parseConfig rejects partial input', () => {
// This test verifies that the type system rejects incomplete config
expectTypeOf({ apiUrl: 'http://example.com' }).not.toMatchTypeOf<ParsedConfig>();
});Run with vitest typecheck or vitest --typecheck.
The Pragmatic Exception
There's one legitimate case to relax strict mode: third-party libraries with broken type definitions. If @types/some-library ships with any-typed returns that cause cascading errors, use module augmentation rather than disabling strict mode globally:
// tests/type-overrides/some-library.d.ts
import 'some-library';
declare module 'some-library' {
interface SomeClass {
methodWithBrokenTypes(): ActualReturnType; // Override the broken any type
}
}Fix the types at the boundary, not the compiler setting.
What Strict Mode Finds in Tests
The most common bugs strict mode surfaces in test files:
.find()results used without null checks — the test assumes the fixture contains what it thinks it does- Array access at fixed indices — assuming
results[0]exists after an async operation - Mock return values with wrong shapes — mocking
UserService.findByIdto return{ id: '123' }instead of a fullUser - Optional properties treated as required — building a test fixture without all required fields
- Unhandled promise rejections — async test helpers that return
Promise<void>called withoutawait
Each of these is a real bug that strict mode catches at compile time instead of runtime. Enable strict mode in your test tsconfig, invest two hours fixing the compilation errors, and your test suite will find more bugs with less maintenance.