Sikau

Advanced JavaScript · Day 25 · about 30 min

Testing your code

Write checks that prove your code works.

Every Check button is a test

Every time you pressed "Check my code" in Sikau, small automated tests ran against your code. Professionals write their own: an automated test calls your function and compares the result with what it should be.

A tiny test runner

function assertEqual(actual, expected, label) {
  const ok = JSON.stringify(actual) === JSON.stringify(expected);
  console.log((ok ? "✓ " : "✗ ") + label + (ok ? "" : ` — got ${JSON.stringify(actual)}`));
  return ok;
}

const slugify = (s) => s.trim().toLowerCase().replaceAll(" ", "-");

assertEqual(slugify("Hello World"), "hello-world", "basic");
assertEqual(slugify("  Trim Me "), "trim-me", "trims spaces");
assertEqual(slugify("Two  Spaces"), "two-spaces", "squashes double spaces");
  • Test the normal case, the edges (empty, zero, huge) and bad input.
  • Keep each test small and independent.
  • When you find a bug, write a failing test first, then fix the code until it passes.

Real projects use test frameworks like Vitest or Jest, which add nicer reports — but the idea is exactly this.

The rest of this lesson

  • What makes a good testexplain
  • Tests as a safety netexplain
  • Which test is missing?predict
  • Pick the test casematch
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 27 lessons of Advanced JavaScript