Hacker News new | ask | show | jobs
by simonw 495 days ago
If you value red green refactoring then you should write the tests first.

I only use that technique for pieces of code that really fit that well - usually functions that have a very strong relationship between their input and output - so I'll write tests first for those, but not for most of my other stuff.

1 comments

Well ok...but then what kind of code doesnt it fit well?

Almost every user story I follow in production code follows the form of given/when/then scenario which can always be transformed into a test of some kind (e2e, integration, sometimes even unit).

Where it's something like "do x, y and z and then a graph appears" I find TDD with a snapshot test with, say, playwright works best.

I'm talking about strict test-first development here, where you write the tests before you write the implementation.

If you're using snapshot tests (a technique I really like) surely you can't write the tests before the implementation, because you need the implementation in order to generate the snapshot?

(This is what I hate about the term TDD: sometimes it means test-first, sometimes it doesn't - which leads to frustrating conversations where people are talking past each other.)

You need the final implementation before taking the final snapshot but you can write the entire test up front (given/when). The snapshot artefact is generated not written (often in a different file entirely), so Id argue it still fits the definition cleanly.

I agree that "unit test"/"integration test" as a definition sucks horribly and leads to people talking past each other, but I think with TDD the main issue is that lots of people have developed a fixed and narrow idea of the kind of test you are "supposed" to write with it which makes the process miserable if the type of code doesnt fit that type of test.

The whole idea of a unit test being "the" kind of "default" test and being "tests a class/method as a unit" definitely needs to die.