Flaky Test Analyzer
Skill9 starsChanged 8 months agoMITView on GitHub
Diagnoses why tests pass inconsistently and suggests fixes for timing, ordering, and state isolation issues.
1 other project uses a version of this.
Adopted by
Most recently taken up by
- anhtester/ClaudeCode_Playwright_Demotheir own version, first seen May 15, 2026
Other versions1 project uses a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 1
- anhtester/ClaudeCode_Playwright_Demo★ 3same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository61 other files it gives its agents.
- Accessibility Audit HelperSkill
- Agent Context File WriterSkill
- Agent Evaluation Framework BuilderSkill
- AI Feature Spec WriterSkill
- API Documentation GeneratorSkill
- REST API Endpoint DesignerSkill
- Architecture ExplainerSkill
- Article RepurposerSkill
- Auth Flow PlannerSkill
- Blog Outline GeneratorSkill
- Breaking Change DetectorSkill
- Bug Root Cause AnalyzerSkill
- Caching Strategy AdvisorSkill
- Changelog CuratorSkill
- Code Review ChecklistSkill
- Database Schema ReviewerSkill
- Docker Compose GeneratorSkill
- Documentation Gap FinderSkill
- Edge Case DiscoverySkill
- Error Log SummarizerSkill
- FAQ GeneratorSkill
- Form UX OptimizerSkill
- Git Commit WriterSkill
- Hallucination Risk ReviewerSkill
- Hybrid Search ArchitectSkill
- Incident Postmortem WriterSkill
- Issue to PR PlannerSkill
- Landing Page Copy ImproverSkill
- LangGraph State Machine DesignerSkill
- LLM Cost OptimizerSkill
- LLM Tracing and Observability SetupSkill
- MCP Integration AssistantSkill
- MCP Server BuilderSkill
- Migration Guide WriterSkill
- Newsletter Summary WriterSkill
- Observability ChecklistSkill
- Playwright Test BuilderSkill
- PR Description WriterSkill
- Prompt Injection Defense AuditorSkill
- Prompt RefinerSkill
- Prompt Version Control WorkflowSkill
- RAG Chunking Strategy AdvisorSkill
- RAG Workflow PlannerSkill
- React Component ReviewerSkill
- README WriterSkill
- Refactor PlannerSkill
- Release Notes GeneratorSkill
- Responsive Layout ReviewerSkill
- SDK Quickstart WriterSkill
- SEO Content OptimizerSkill
- SEO Metadata GeneratorSkill
- Social Post Thread WriterSkill
- Sprint Summary GeneratorSkill
- SQL Query OptimizerSkill
- Stack Trace AnalyzerSkill
- Technical Blog Post WriterSkill
- Tech Debt AuditorSkill
- Troubleshooting Guide BuilderSkill
- Unit Test ImproverSkill
- Unit Test WriterSkill
- The first 60 shown.
The file
Show its rules and text
We split this skill into the rules it gives an agent
14 rules. About 0 are common, 11 are distinctive, and 3 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈11
Distinctive · estimate
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 19
Use this when a test is unreliable in CI, when a test passes locally but fails on the CI server, or when a test fails intermittently with …
- Very specific: line 39
Add the instructions below to your .cursorrules or paste them into the Cursor AI pane.
- Distinctive: line 47
When asked to diagnose a flaky test, follow this process:
- Distinctive: line 51
Before analyzing, ensure you have:
- Distinctive: line 58
If any of these are missing, ask for them.
- Distinctive: line 62
Check for each of these flakiness patterns in order:
- Distinctive: line 80
Test A passes only when test B ran first (shared setup)
- Distinctive: line 81
Test A fails when run in isolation but passes in the suite
- Distinctive: line 97
Test timeouts set too low for the environment
- Distinctive: line 101
After identifying which category applies, pinpoint the exact line(s) causing the flakiness.
- Very specific: line 112
Use jest.useFakeTimers() consistently and advance time explicitly
- Distinctive: line 113
Use a test database that's wiped between runs
- Very specific: line 115
Add proper await to async operations
- Distinctive: line 209
Always provide the failure message, not just "it fails." The exact error often reveals the category immediately.
≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Flaky Test Analyzer
What this skill does
This skill directs the agent to diagnose flaky tests — tests that sometimes pass and sometimes fail without any code changes. It examines the test code, the code under test, and the failure patterns to identify the root cause category (timing, shared state, ordering, network, randomness, etc.) and then suggests targeted fixes that make the test deterministic.
Use this when a test is unreliable in CI, when a test passes locally but fails on the CI server, or when a test fails intermittently with no obvious pattern.
How to use
Claude Code / Cline
Copy this file to .agents/skills/flaky-test-analyzer/SKILL.md in your project root.
Then ask:
- "Use the Flaky Test Analyzer skill on
tests/checkout.test.ts— it fails about 1 in 5 runs in CI." - "This test passes locally but fails in CI. Use the Flaky Test Analyzer skill to diagnose it."
Provide:
- The test file (or the specific test that's flaky)
- The failure message when it does fail
- How often it fails (every time? 1 in 10? only in CI?)
- Any observations about when it fails (after a specific other test? at a specific time of day?)
Cursor
Add the instructions below to your .cursorrules or paste them into the Cursor AI pane. Provide the test code and failure output.
Codex
Paste the test file, the failure message, and any relevant context. Ask Codex to follow the instructions below.
The Prompt / Instructions for the Agent
When asked to diagnose a flaky test, follow this process:
Step 1 — Gather information
Before analyzing, ensure you have:
- The full test code, including
beforeEach,afterEach,beforeAll, andafterAllhooks - The code under test (the function or module being tested)
- The error message when the test fails (not just "test failed")
- The failure frequency pattern (always, sometimes, CI only, etc.)
- The test framework and any relevant configuration (jest.config.js, vitest.config.ts, etc.)
If any of these are missing, ask for them.
Step 2 — Identify the flakiness category
Check for each of these flakiness patterns in order:
Timing and async issues
setTimeoutorsetIntervalwith hardcoded delays that may not be long enough- Missing
awaiton async operations - Polling for a condition with a timeout that's too short
- Fake timers (
jest.useFakeTimers) mixed with real timers - Tests that depend on the exact time of day or system clock
Shared state and isolation
- Global variables modified in one test but not reset before the next
- Database records created in one test that affect another
- File system changes not cleaned up
- In-memory caches not cleared between tests
- Static class properties mutated during tests
- Singleton services not reset
Test ordering dependencies
- Test A passes only when test B ran first (shared setup)
- Test A fails when run in isolation but passes in the suite
- Tests that rely on a specific execution order
External dependencies
- HTTP calls to real external APIs (network flakiness, rate limits)
- File system reads of files that may not exist in CI
- Environment variables that differ between local and CI
- Random number generation with no seed
Race conditions in the code under test
- Concurrent operations with no locking
- Event listeners that fire at unpredictable times
Promise.allwith side effects that interfere
Test framework issues
- Snapshot files out of date
- Test timeouts set too low for the environment
Step 3 — Diagnose the specific test
After identifying which category applies, pinpoint the exact line(s) causing the flakiness. Explain:
- What assumption the test is making
- Why that assumption is sometimes wrong
- What condition makes it fail vs pass
Step 4 — Recommend a fix
Provide a concrete, specific fix. Common fixes include:
- Replace
setTimeout(() => ..., 100)withwaitFor(() => ...)orvi.runAllTimers() - Add
afterEach(() => { jest.clearAllMocks(); db.cleanup(); }) - Mock the external API instead of calling it
- Use
jest.useFakeTimers()consistently and advance time explicitly - Use a test database that's wiped between runs
- Set a random seed for deterministic random values
- Add proper
awaitto async operations
Step 5 — Format the output
## Flaky Test Diagnosis
### Test
`[test name]` in `[file path]`
### Failure Pattern
[How often it fails, under what conditions]
### Root Cause Category
[Timing / Shared state / Test ordering / External dependency / Race condition / Other]
### Root Cause
[2–3 sentences explaining exactly why the test is flaky — what assumption it makes and why that assumption sometimes fails]
### The Problematic Code
[Quote the specific lines that cause the flakiness]
### Fix
[The specific change(s) to make the test deterministic, with code]
### Why This Fix Works
[1–2 sentences explaining why the fix eliminates the non-determinism]
### Prevention
[1 sentence on how to avoid this class of flakiness in future tests]Example
Input to Agent:
"Use the Flaky Test Analyzer skill. This test fails about 1 in 4 runs in CI:
it('sends a welcome email after registration', async () => { await registerUser({ email: 'test@example.com', password: 'abc123' }); setTimeout(() => { expect(emailService.send).toHaveBeenCalledWith({ to: 'test@example.com', subject: 'Welcome!' }); }, 200); }); ```"
Output from Agent:
Flaky Test Diagnosis
Test
sends a welcome email after registration—user.test.tsFailure Pattern
Fails ~25% of runs, more often in CI than locally.
Root Cause Category
Timing / async issue
Root Cause
The
expectinsidesetTimeoutis not awaited, so Jest considers the test done as soon asregisterUserresolves — the assertion runs 200ms later, after Jest has already moved on. When the event loop is busy (common in CI), the 200ms delay may not be enough, and even when it fires, Jest may no longer be tracking it.The Problematic Code
setTimeout(() => { expect(emailService.send).toHaveBeenCalledWith(...); }, 200);Fix
it('sends a welcome email after registration', async () => { await registerUser({ email: 'test@example.com', password: 'abc123' }); await waitFor(() => { expect(emailService.send).toHaveBeenCalledWith({ to: 'test@example.com', subject: 'Welcome!' }); }); });If
waitForisn't available (non-React project), usejest.runAllTimers()withjest.useFakeTimers()or poll manually with a small helper.Why This Fix Works
waitForrepeatedly retries the assertion until it passes or a timeout is reached, making the test resilient to variable execution timing.Prevention
Never put
expect()calls inside a rawsetTimeout— always await the operation that triggers the side effect, or usewaitFor.
Notes
- Always provide the failure message, not just "it fails." The exact error often reveals the category immediately.
- "Passes locally, fails in CI" is usually a timing issue (slower machines) or a missing environment variable.
- "Fails only when run with other tests" is almost always a shared state issue — try running the failing test in isolation first to confirm.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

