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:
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)
- Red: write a test for behavior that doesn't exist yet. Watch it fail.
- Green: write the simplest code that makes it pass.
- 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 doneStep 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.
function slugify(title) {
return title;
}
Output appears here. Press Run or Ctrl/⌘ + Enter.
Step 2 of 2 · Test with a fake
welcome(user, sendEmail) should call sendEmail(address, message) once with the user's email and the message "Welcome, <name>!". It should not send anything if the user has no email.
Because the email sender is passed in, the tests can use a fake one that just records calls.
function welcome(user, sendEmail) {
}
Output appears here. Press Run or Ctrl/⌘ + Enter.
✅ Check your understanding
What's the TDD cycle?
Why pass dependencies (like an email sender) into a function?
Create a free account to track your progress.