Lesson 6 of 6 · 12 min · 2 hands-on steps

Unit Testing & Test-Driven Development

Write tests first, then make them pass. The habit that makes you trustworthy on a team.

You've been using tests all along

Every exercise on this site checks your code with unit tests: small, automatic checks of one piece of code. Here's what those tests look like:

JavaScript · try it
function add(a, b) {
  return a + b;
}

const tests = [
  ["adds positives", add(2, 3) === 5],
  ["adds negatives", add(-1, -1) === -2],
  ["adds zero", add(5, 0) === 5],
];
for (const [name, pass] of tests) console.log(pass ? "✓" : "✗", name);

At work you'd use a framework like Jest or Vitest (JavaScript) or pytest (Python), but the idea is identical.

What makes a good test

  • Tests one behavior, with a name that says what
  • Covers the normal case, edge cases (empty, zero, huge) and error cases
  • Is fast and gives the same result every time

Test-driven development (TDD)

  1. Red: write a test for behavior that doesn't exist yet. Watch it fail.
  2. Green: write the simplest code that makes it pass.
  3. Refactor: clean up, keeping the tests green.

TDD forces you to decide what the code should do before how. It also leaves behind a safety net, so future changes (including AI-generated ones) can be checked instantly.

Fakes for things you don't want to really do

You don't want tests that send real emails or charge real cards. Pass those dependencies in, and in tests pass a fake that records what happened. That's what the second practice step does.

Teams trust developers whose pull requests come with tests. It's one of the fastest ways to stand out as a junior.

🧪 Practice: 2 steps

0 / 2 done

Step 1 of 2 · Make the tests pass (TDD)

In TDD you start from tests. These are the tests for slugify(title), which turns a title into a URL-friendly slug:

slugify("Hello World")          // "hello-world"
slugify("  Learn  JS  Fast ")   // "learn-js-fast"
slugify("C++ & Python!")        // "c-python"
slugify("")                     // ""

Write slugify until every test is green.

JavaScript
function slugify(title) {
  return title;
}

Output appears here. Press Run or Ctrl/⌘ + Enter.

✅ Check your understanding

  1. What's the TDD cycle?

  2. Why pass dependencies (like an email sender) into a function?

Create a free account to track your progress.