A unit test executes a small part of an application and checks whether its behavior matches an expected result. In TypeScript projects, the test ultimately runs against compiled JavaScript, so it cannot verify features enforced only by the TypeScript compiler. section 6.4
A practical Jest setup uses:
- Jest as the testing framework, ts-jest to compile TypeScript before testing, and @types/jest for Jest API definitions. section 6.4
- Test files named with the .test.ts extension, conventionally placed beside the implementation files they test. section 6.4.2
- The test function to describe a case and expect with matcher functions such as toBe, toEqual, toMatch, and toContain. section 6.4.2
- Watch mode to rerun tests after source or test changes and report passing or failing expectations. section 6.4.3
Testing a calculation function
Create src/calc.test.ts beside calc.ts, import sum, invoke it with 10, 20, and 30, and assert that the result is 60. If sum returns 70, Jest identifies the expected value, received value, and failing assertion. Fix the implementation or update the test when the intended behavior changes. section 6.4.2 section 6.4.3
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);
});
Inspect the complete TypeScript test listing for the calculation example. 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
Inspect the npm commands that install Jest, ts-jest, and the Jest type definitions. section 6.4








