Why tests become flaky
A flaky test passes when it wants and fails without a code change. It is not "going to fix itself": every flaky test erodes trust in the whole run.
Where instability comes from
- Time. A fixed
sleepis not connected to data readiness. - Order. Tests share state and depend on who ran first.
- Network. A live API or a database that is sometimes slower.
- Races. Two threads write to the same place without synchronisation.
How to treat it
- Replace
sleepwith waiting for a condition. - Isolate data: each test prepares its own environment.
- Mock external services: the test should verify your logic, not the internet.
- Make the race reproducible: a barrier at the start and a controlled switch point instead of "run it a hundred times and hope".
What to do in production
Find the cause first, then fix it. A timeout failure is not a reason to increase the timeout forever; it is a signal that the condition is not being checked.