Flaky Tests and Deterministic Fixes
Build a working model of automated testing from assertions to unit, component, API, integration, contract and end-to-end tests, then apply it to a single progressive task-board capstone where each milestone adds a real defect, a failing test, a corrected implementation and an expected result.
What you will be able to do
#- Recognize the common sources of test flakiness.
- Diagnose a flaky test from its failure pattern.
- Fix flakiness at the source instead of adding retries.
Overview
#A flaky test is a broken test
A flaky test passes sometimes and fails other times with no code change. It trains the team to ignore red, which is worse than having no test. The fix is always to remove the nondeterminism, never to retry until green.
Common sources
Time: the real clock moves between runs. Order: a test depends on another test's side effect. Concurrency: two async operations race, and the test assumes one finishes first. Network: a real call is slow or returns different data. Randomness: an unseeded random value changes inputs. Resource limits: a test passes on a fast machine and times out on a slow one. Each source has a deterministic fix.
Time: inject a clock
Replace Date.now() with an injected clock. The test supplies a fixed time, so the result is identical on every run.
Order: isolate state
Create fresh state per test. If a test must run after another, they are secretly one test and should be merged or made independent.
Concurrency: wait for a condition, not a duration
A race appears when a test asserts before an async operation completes. Await the operation or wait for an observable condition. A setTimeout(100) is a guess that fails under load.
Diagnose from the pattern
Fails only in CI: environment difference such as timezone, locale or CPU speed. Fails only when the full suite runs: shared state or order dependence. Fails intermittently everywhere: a race or an unseeded random. The failure pattern narrows the cause faster than reading the code.
Quarantine is temporary
Moving a flaky test out of the blocking suite stops the noise, but it is not a fix. Track it with an owner and a deadline. A quarantined test that nobody fixes is a deleted test with extra steps.
Retries hide the problem
A retry that turns a flaky test green hides a real race or leak that will also affect users. Retries may be acceptable as a temporary signal while the fix is in progress, but they must not be the permanent answer. A test that needs a retry to pass is not passing.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
A test asserts a value that is set inside a `setTimeout(fn, 0)` but does not await anything. What is the likely outcome across runs?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.javascriptlet done = false; setTimeout(() => { done = true; }, 0); console.log(done);Exercise 2Explain
Explain why a test that fails only in CI is usually a determinism problem, not a CI problem.
Reveal the reference answer
reference.javascriptCI differs from the developer machine in timezone, locale, CPU speed, available memory and parallelism. A test that depends on the real clock, the default timezone, a fixed delay or shared state will pass on one environment and fail on another. The difference is in the environment, but the defect is in the test's dependence on that environment. The fix is to remove the dependency, not to change CI.The answer should name the environment differences and locate the defect in the test's nondeterminism.
Exercise 3Implement
Implement `createClock(start)` returning `{ now, advance }` where `now()` returns the current virtual time and `advance(ms)` moves it forward. `const c = createClock(1000); c.advance(500); console.log(c.now())` should print `1500`.
starter.javascriptfunction createClock(start) { // your code here }Reveal the reference answer
reference.javascriptfunction createClock(start) { let current = start; return { now: () => current, advance: (ms) => { current += ms; }, }; }Authored expected output: 1500
The clock keeps its own time in a closure. now reads it and advance moves it deterministically, so code that accepts this clock instead of the real one produces identical results on every run.
Exercise 4Debug
This test is flaky because it uses a fixed sleep to wait for an async result. Replace the sleep with a condition wait so `console.log(ready)` prints `true` reliably.
starter.javascriptasync function test() { let ready = false; setTimeout(() => { ready = true; }, 50); await new Promise((r) => setTimeout(r, 100)); console.log(ready); } test();Reveal the reference answer
reference.javascriptasync function test() { let ready = false; setTimeout(() => { ready = true; }, 50); while (!ready) { await new Promise((r) => setTimeout(r, 5)); } console.log(ready); } test();Authored expected output: true
The fixed 100ms sleep is a guess that can fail under load. Polling the condition resolves as soon as ready becomes true, so the test is fast on a quick machine and still correct on a slow one.
Exercise 5Test
Write a test that proves a seeded random picker returns the same sequence for the same seed.
starter.javascriptfunction createPicker(seed) { let state = seed; return () => { state = (state * 1103515245 + 12345) % 2147483648; return state; }; }Reveal the reference answer
reference.javascriptfunction assertEqual(actual, expected, label) { if (actual !== expected) throw new Error(label + ': expected ' + expected + ' but got ' + actual); } const a = createPicker(42); const b = createPicker(42); assertEqual(a(), b(), 'first value matches'); assertEqual(a(), b(), 'second value matches'); const c = createPicker(43); assertEqual(createPicker(42)() === c(), false, 'different seed differs'); console.log('determinism verified');Authored expected output: determinism verified
Two pickers with the same seed produce the same sequence, which is what makes the code deterministic and testable. The third assertion confirms the seed actually influences the output, so the test is not trivially true.
Exercise 6Interview
In an interview, explain your process for handling a flaky test in a shared suite.
Reveal the reference answer
reference.javascriptFirst I confirm it is flaky by rerunning and by running it alone versus in the full suite. I read the failure pattern to narrow the cause: only in CI suggests environment, only in the full suite suggests shared state, intermittent everywhere suggests a race or unseeded random. I fix the root cause by injecting time, isolating state or waiting on a condition. If I must unblock the team immediately, I quarantine it with an owner and a deadline, and I never treat a retry as the fix.The answer should include reproduction, pattern-based diagnosis, a root-cause fix, and time-boxed quarantine with an owner.
Common misconceptions
#- Retrying a flaky test is a valid permanent fix.
- A test that fails only in CI is a CI problem.
- Quarantining a flaky test closes the issue.
Follow-up practice
#- testing-capstone-quality-task-board
- testing-ci-gates
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.