← Back to TypeScript Course | Chapter 24: Testing TypeScript | Lesson 2 of 6

ts-jest Setup

ts-jest is a Jest transformer that can compile TypeScript test files for Jest. A typical setup includes Jest, TypeScript, ts-jest, and a Jest configuration that tells Jest how to transform TypeScript files.

Install Required Packages

Setting up ts-jest requires installing jest, ts-jest, and @types/jest as dev dependencies, since Jest itself doesn't understand TypeScript syntax without a transform.

Example: Install Required Packages

typescript
// npm install --save-dev jest ts-jest @types/jest
console.log("jest, ts-jest, and @types/jest are needed as dev dependencies");

Jest Configuration

Jest's configuration needs a transform entry pointing .ts/.tsx files at ts-jest, which tells Jest to compile each test file through the TypeScript compiler before executing it.

Example: Jest Configuration

typescript
// jest.config.js
// module.exports = { transform: { "^.+\\.tsx?$": "ts-jest" } };
console.log("transform maps .ts/.tsx files through ts-jest before running");

TypeScript Compiler Options

The TypeScript compiler options used for tests can differ slightly from your app's tsconfig.json — for example relaxing isolatedModules for faster test compilation — configured either inline or in a dedicated test tsconfig.

Example: TypeScript Compiler Options

typescript
// jest.config.js
// globals: { "ts-jest": { isolatedModules: true } }
console.log("Test compiler options can relax settings for faster runs");

Test File Structure

Test files conventionally live alongside the code they test (Component.test.ts next to Component.ts) or in a mirrored __tests__ directory, both of which Jest's default file-matching picks up automatically.

Example: Test File Structure

typescript
// Component.ts
// Component.test.ts   (or __tests__/Component.test.ts)
console.log("Jest auto-discovers *.test.ts files or __tests__ folders");

Running Tests and Type Checks

Running jest executes your tests, while a separate tsc --noEmit command catches type errors that ts-jest's per-file transform might miss, since ts-jest doesn't perform full-project type checking by default.

Example: Running Tests and Type Checks

typescript
// npm test          (runs jest)
// npx tsc --noEmit  (full-project type check ts-jest's transform may miss)
console.log("Run both jest and tsc --noEmit for full coverage");
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.