Advanced level · Module 1: Testing JavaScript · Lesson 4 of 4
Test-Driven Development
Write a failing test first, make it pass with the simplest code, then refactor — and know when this approach helps most.
In this lesson you will
- Apply the red–green–refactor cycle
- Decide when test-driven development is worthwhile
Key concepts
red–green–refactorsmallest steprefactoring with testsregression test
The lesson
In test-driven development (TDD) you write a test for the next small behaviour, see it fail (red), write just enough code to pass (green), then improve the code while the tests stay green (refactor).
TDD works best for logic with clear inputs and outputs, such as calculations, validation rules and parsers. It forces small steps and produces a test for every behaviour.
For bugs, always start by writing a test that reproduces the bug. It fails, you fix the code, it passes, and it stays in the suite as a regression test.
Step by step
- Write a failing test for a visit validation rule.
- Make it pass with minimal code.
- Add the next rule with a new failing test.
- Refactor the validator with all tests green.
Practice activity
Use TDD to build a validator for household visit records with at least six rules.
Expected result: Six or more rules, each introduced by a test written first, with a clean final implementation.
Check your understanding
-
What are the three steps of the TDD cycle?
Show answer
Red (failing test), green (make it pass), refactor.
-
What kind of code suits TDD best?
Show answer
Logic with clear inputs and outputs, such as calculations and validation.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.