Tests

TDD in practice: red, green, refactor

TDD — Test-Driven Development — flips the intuitive order: you write the test before the code. It sounds counterintuitive, but it is one of the techniques that most improves design and confidence in what you ship.

The cycle: Red, Green, Refactor

  1. Red: write a failing test — it describes behavior that doesn't exist yet.
  2. Green: write the minimum code to make the test pass. No frills.
  3. Refactor: improve the code with the safety net of a green test.
// 1. Red — the test fails because the function doesn't exist
test('adds two numbers', () => {
  expect(soma(2, 3)).toBe(5);
});

// 2. Green — the minimum to pass
function soma(a, b) { return a + b; }

// 3. Refactor — now safe to evolve

Why it works

  • Usage-driven design: you design the API thinking about whoever calls it.
  • Natural coverage: the code is born tested, with no "I'll write the test later".
  • Short feedback: errors show up in seconds, not in production.
  • Living documentation: the tests describe the expected behavior.
TDD isn't about testing — it's about design. The tests are the happy side effect.

When to go easy

TDD shines in business logic and complex rules. For throwaway prototypes or exploratory code, it can be overkill. The key is to use the right tool for the context — not to turn TDD into dogma.

Conclusion

Practicing the red-green-refactor cycle trains the team to think in terms of behavior and to keep the code always under a safety net. It's an investment that pays off with the first painless refactoring.

Read also

Back to the blog