liveBook · Manning

Unit test

As explained in Essential TypeScript 5, Third Edition

A unit test is an automated test that evaluates a small, isolated unit of program behavior.

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

How Essential TypeScript 5, Third Edition covers it

How deep it goes
Explains setup, file conventions, assertions, watch execution, and failure correction, but stops short of teaching unit-testing theory.
Examples
Uses a calc.test.ts file to test sum, Jest matchers, watch output, and deliberate implementation and expectation changes.
What you can do after
Apply it via Jest to write, execute, monitor, and diagnose focused tests for TypeScript application behavior.
How it connects
Connects unit tests with Jest, TypeScript compilation, JavaScript runtime environments, assertions, and debugging.

Also explained in

Compare how 9 books explain unit test →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Essential TypeScript 5, Third Edition. The section links point to the parts of the book it draws on.