Node.js course · Part 7: Tests worth having · lab 7 of 9
Tests that actually catch things
Not how to write a test, which takes five minutes, but how to write ones worth having: cases chosen to catch real bugs, tests that survive a rewrite, and fakes at the edges so the slow parts stay out.
By the end you can
- Choose test cases by what could break, not by what is easy to assert
- Write tests that survive a rewrite of the code underneath
- Replace the database, the clock and the network with fakes
- Say why a test suite that never fails is worth nothing
Easier if you did first
step 1 of 4
What a test is for
A test is not there to prove the code works today. You already know that; you just ran it. It is there to tell you, in eight months, that the change you are about to ship breaks something you have forgotten about.
That reframing decides everything. A test earns its place by failing when something real breaks, and only then. A test that never fails is a maintenance cost pretending to be safety, and a test that fails at random is worse, because it teaches the team to ignore red.
The shape is always the same three parts: set up the situation, do the one thing, check the result. Keeping them visibly separate is most of what makes a test readable a year later.
Four questions.
What these words mean
- unit test
- Tests one piece on its own, with its surroundings faked.
- integration test
- Tests the pieces together, usually with a real database.
- arrange, act, assert
- Set up, do the thing, check the result.
- flaky
- Passes or fails at random. Worse than no test.
- regression test
- A test written from a bug, so it cannot come back.
question 1 of 4
Your suite covers 100% of lines and a bug ships anyway. How?
question 2 of 4
Which case is most worth a test?
question 3 of 4
You rewrite a function's internals without changing what it returns. Your tests fail. What does that mean?
question 4 of 4
A test fails about one run in twenty. What should you do?