How to Automatically Retry Flaky Tests with GitHub Actions
Retrying only the tests that failed turns a transient flake into a pass without re-running the whole suite.
You can retry at the test level with jest.retryTimes(2), or run the suite, then re-run failures with jest --onlyFailures. Reserve retries for genuinely flaky tests, since blanket retries hide real regressions.
Steps
- Add
jest.retryTimes(2, { logErrorsBeforeRetry: true })in a setup file for in-suite retries. - Or run the suite once and re-run only failures with
jest --onlyFailures. - Treat a test that needs retries as a bug to fix, not a permanent crutch.
Workflow
.github/workflows/ci.yml
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- name: Run tests, retrying failures once
run: npx jest || npx jest --onlyFailuresGotchas
--onlyFailuresneeds Jest's cache, so do not clear it between the two runs.- Auto-retry masks flakiness; track which tests retry so you can fix root causes.
- Latchkey managed runners also auto-heal transient infrastructure failures, which is a different layer from test-level retries.
Related guides
How to Quarantine a Known Flaky Test with GitHub ActionsIsolate a known-flaky test in GitHub Actions by tagging it and running the quarantined set as a non-blocking…
How to Run Playwright End-to-End Tests with GitHub ActionsRun Playwright end-to-end tests in GitHub Actions, installing browsers with their system dependencies and upl…