How to Run Tests in Random Order to Surface Flakes in CI
Randomizing order surfaces hidden test coupling, and printing the seed lets you replay the exact failing order.
Use pytest-randomly (or Jest test shuffling) to run tests in a random but reproducible order. When a run fails, rerun with the printed seed to reproduce and then fix the coupling.
Steps
- Enable random ordering with a seeded plugin.
- Capture the seed printed on each run.
- Replay the failing seed to reproduce, then fix the dependency.
Randomize and replay (pytest)
Terminal
pip install pytest-randomly
pytest # prints: Using --randomly-seed=931204
pytest -p randomly -p no:cacheprovider --randomly-seed=931204Shuffle Jest tests
jest.config.js
// jest.config.js
module.exports = { randomize: true, seed: 1 };
// or: npx jest --shard=1/1 --seed=1Gotchas
- Random order that always passes proves nothing; you need the failing seed to fix anything.
- Always log the seed, or a random failure becomes impossible to reproduce.
Related guides
How to Deflake Order-Dependent Tests in CIDeflake order-dependent tests in CI by finding tests that only pass in a specific sequence and removing the h…
How to Deflake a Test by Fixing Shared State in CIDeflake a test by isolating shared state, resetting databases, caches, and globals between tests so leftover…
How to Bisect a Flaky Test in CIBisect a flaky test in CI by narrowing which sibling test or which commit introduced the flakiness, using tar…