Jest is a JavaScript testing framework for defining unit tests, making assertions, and reporting whether application behavior matches expectations. TypeScript tests must be compiled to JavaScript before execution; ts-jest performs that compilation, while @types/jest supplies TypeScript definitions for the Jest API. section 6.4
Set up Jest in the tools folder with these development packages:
- jest@29.4.3 provides the testing framework. section 6.4
- ts-jest@29.0.5 compiles TypeScript files before tests run. section 6.4
- @types/jest@29.4.0 provides TypeScript definitions for Jest’s API. section 6.4
- jest.config.js identifies project roots and routes .ts and .tsx files through ts-jest. section 6.4.1
Testing a calculation
Place calc.test.ts beside the related file in src. Import sum, call it with three values, and use expect with the toBe matcher to assert the result: sum(10, 20, 30) should produce 60. Jest’s matchers also test equality, regular-expression matches, definedness, truthiness, containment, and numeric comparisons. section 6.4.2
Listing 6.14 Adding packages to the project
npm install --save-dev jest@29.4.3 npm install --save-dev ts-jest@29.0.5 npm install --save-dev @types/jest@29.4.0
View the package installation commands for Jest, ts-jest, and @types/jest. section 6.4
Listing 6.15 The contents of the jest.config.js file in the tools folder
module.exports = {
"roots": ["src"],
"transform": {"^.+\\.tsx?$": "ts-jest"}
}
View the complete jest.config.js configuration for roots and TypeScript transformation. section 6.4.1
Listing 6.16 The contents of the calc.test.ts file in the src folder
import { sum } from "./calc";
test("check result value", () => {
let result = sum(10, 20, 30);
expect(result).toBe(60);
});
View the complete calc.test.ts example using test, expect, and toBe. section 6.4.2
Listing 6.17 Starting the unit test framework in watch mode
npx jest --watchAll
Run npx jest --watchAll to execute tests continuously as files change; failed output identifies expected and received values. section 6.4.3




