last updated: August 9, 2022
1 minute read
Test-Driven Refactoring
In my mind, test-driven development has given tests a bad reputation.
For reference, Wikipedia defines test-driven development as:
a software development process relying on software requirements being converted to test cases before software is fully developed
Or in other words, writing your tests before writing your code.
The purported benefits are less-buggy code and a smoother dx – but in my experience, this rarely pans out.
Part of the philosophy of test-driven development is that by solely testing software requirements, you can avoid testing implementation details. In fact, test-driven development relies on this pattern – you can't test implementation details you haven't written yet!
In principle, I would agree with this. If you truly only test software requirements, you could refactor the implementation behind your code without rewriting a single test - what a dream.
Unfortunately, this is rarely possible. When testing frontend code, for example, you sometimes need to hook into DOM elements directly in your tests. Other times, you may even want to test implementation details – was an api call made in the correct circumstances? That's an important detail that's difficult to test before you've written your code.
That being said, I still very much value the utility of tests – but for refactoring, not development.
I'm a big believer in being unafraid of my code. If I want to update a feature, refactor a shared utility, I don't want to be afraid of silently breaking my app. I need the freedom to update my code when I think best, and tests give me the confidence necessary to make these changes.
To hammer in the point, I'm not afraid of breaking my app; I'm afraid of silently breaking my app. If I have good test coverage, that'll never happen.
So for those who are skeptical of test-driven development: don't give up on tests altogether. Write tests to catch regressions, not to speed-up writing original code. Adopt test-driven refactoring, not test-driven development.
you might also like:
Server Side Rendering vs React Server Components
November 08, 2022
Comparing, contrasting, and exploring how the two can be used to compliment one another