Easier Way to Learn TDD

Learning Test Driven Development (TDD) is hard. I have a decade+ of “Test Last” “Test After” content on my blog and YouTube, none of it “Test First” until much later in my career. So here’s a 3 phase process to ease into it. I’m assuming you already know how to setup unit testing frameworks (Jest/Vitest/Mocha/Jasmine, etc) and use assertions (expect, assert, etc).

Phase 1: Unit Testing

  1. Write some code you’re proud of, UI or API.
  2. Write a single happy path test for it and make it pass.
  3. Comment out the code, but don’t delete files. Use the commented out code as reference if you need to. Keep your test as is.
  4. Make your test pass again. Compare the code you wrote with your original code.

Phase 2: Designing Through Testing

Cool, now that you know how to write an implementation, redo the above, but hide your code in another file and close it, then DELETE your code in Step 3, keep the tests. You should have an empty file. When you make the test pass, re-open that file you hid, and compare the code you wrote vs. the new code you wrote to make the test pass.

Phase 3: Small Batches

Repeat Phase 2, but this time, try to get the test to pass with the least amount of code. If a function/class method asserts the return is true, then just return true. Track those teency additions all while keeping the test passing, whether manually or git commits. Keep going till you’re done refactoring; you’re happy with the end result. When done, compare both the code and the new code. Also, and key for this phase, try to find the largest or longest time you spent making a change; how could you make this less code in a commit and do it quicker in a smaller batch?

If you can do 1, 2, and 3, then you’re now able to refactor for as long as you like, safely.