Red-Green-Refactor
In one line
The TDD cycle: Red (failing test), Green (passing test), Refactor (improve code while tests pass).
In simple words
Red-Green-Refactor is the rhythm of TDD. It's a three-step cycle you repeat for every feature:
- Red: Write a test for the new behavior. Run it. It fails (red) because the code doesn't exist or doesn't do the right thing yet. This confirms the test is actually testing something.
- Green: Write the minimum code needed to make the test pass. Don't add extra features or complexity — just make it pass. Run the test. It passes (green).
- Refactor: Now that the test passes, improve the code. Rename variables, extract functions, remove duplication. Run the tests after each change. If something breaks, you know immediately.
The cycle ensures you always have working code and a growing test suite. The 'red' step is crucial — if a new test passes immediately, it might not be testing anything new.
Example
javascript
// RED — write a failing test first
test('multiply returns product', () => {
expect(multiply(3, 4)).toBe(12); // fails: multiply not defined
});
// GREEN — write minimum code to pass
function multiply(a, b) {
return a * b;
}
// Run test → passes ✓
// REFACTOR — improve while tests stay green
const multiply = (a, b) => a * b;
// Run test → still passes ✓The TDD cycle in three steps: Red (write a failing test), Green (write just enough code to pass), Refactor (improve the code with the test as a safety net).
Related terms
Related Resources
Related Lessons
- Test-Driven Development
The TDD workflow.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.