×

typescript · level 3 · unit 7 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Unit tests check your code so you do not have to.

A runs one small piece of code with a known input and checks the answer. Professionals keep hundreds of them and run them after every change, so a bug shows up in seconds instead of weeks.

A is the code that runs every test and reports what passed. Ours is tiny. test takes a name and a callback and runs it inside try...catch. assertEqual<T> throws when two values differ, and the generic makes both sides the same type.

function assertEqual<T>(actual: T, expected: T): void {
  if (actual !== expected) {
    throw new Error(`expected ${String(expected)}, got ${String(actual)}`);
  }
}
function test(name: string, run: () => void): void {
  try {
    run();
    console.log(`PASS ${name}`);
  } catch (e) {
    console.log(`FAIL ${name}: ${String(e)}`);
  }
}
test("trims spaces", () => assertEqual(" tea ".trim(), "tea"));

String(e) turns a thrown Error into text like Error: expected 4, got 5.