TDD (test-driven development) means you write a failing test before you write the code that makes it pass. You work in short cycles of three steps:
- Red: write a small test for the next bit of behaviour and watch it fail. Seeing it fail proves the test can catch the missing behaviour.
- Green: write the simplest code that makes the test pass, even if it is not pretty.
- Refactor: clean up the code and the test while the tests stay green. Then repeat.
The benefits:
- The design comes from how the code is used.
- You get a safety net of tests that grows with the code.
- Fewer code paths stay untested.
TDD works especially well for pure logic, reducers and bug fixes. For a bug fix, first write a test that reproduces the bug. For UI exploration, many people write tests just after the code instead. That is fine, as long as the tests exist.
- In TDD you write the failing test first.
- Red: the test fails, and it fails for the right reason.
- Green: write the simplest code that makes the test pass.
- Refactor: clean up the code, with the tests as a safety net.
- TDD is great for bug fixes: first reproduce the bug in a test.
Read more