ts-jest Setup
In this page:
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
// 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
// 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
// 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
// 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
// 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: