Cypress Flake Fixer
GitHubOfficialFirst committed by qlqlmiDistributed by GitHub
- Skill
- Review and audit
- Software development
- MIT
- Low risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
Cypress Flake Fixer is a diagnostic suite designed to audit existing Cypress test projects for common anti-patterns that cause intermittent failures. It provides a zero-dependency scanner that detects problematic code structures like fixed delays, improper command chaining, and conditional testing. The skill offers a structured methodology for replacing these anti-patterns with robust, retry-aware Cypress commands and provides guidance for migrating projects to newer Cypress versions by identifying removed or changed APIs.
What it does
- Scans test files for flake-prone patterns like cy.wait, force: true, and async/await usage
- Identifies deprecated or removed Cypress APIs for major version upgrades
- Provides a systematic workflow to replace brittle waits with network intercepts or state assertions
- Offers specific guidance on fixing detached-from-the-DOM errors
- Includes a baseline measurement process to verify test stability improvements
- Supplies migration paths for sensitive and public environment variables
When to use it
- When tests pass locally but fail intermittently in CI environments
- When a test suite contains excessive hard-coded waits or forced interactions
- When preparing to upgrade a project to Cypress 12 through 16
- When debugging persistent detached-from-the-DOM or timeout errors
- When performing a quality audit of existing end-to-end test code
Advantages
- Improves test reliability without relying on masking failures with retries
- Reduces test execution time by replacing arbitrary delays with event-driven assertions
- Provides actionable, rule-based feedback for specific code anti-patterns
- Facilitates safer major version migrations by flagging breaking API changes
- Encourages better testing practices by exposing underlying application issues
Usage examples
- “Scan my Cypress suite for flaky patterns and deprecated APIs.”
- The tool runs a scan across the project directory, reporting findings categorized by rule, such as CY001 for fixed waits or CY007 for removed APIs, and suggests specific refactoring steps.
- “How do I fix a test that fails with a detached-from-the-DOM error?”
- The skill guides you to identify if the chain is broken by an action that triggers a re-render, suggesting you split the chain or re-query the element after the action.
- “I am upgrading to Cypress 16 and need to migrate Cypress.env.”
- The skill provides instructions on distinguishing between public values using Cypress.expose and sensitive values using the asynchronous cy.env command.
- “Replace a cy.wait(2000) in my checkout test.”
- The skill instructs you to identify the network request or state change the wait was covering and replace it with a specific cy.intercept alias or a DOM assertion.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/github/cypress-flake-fixer/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip cypress-flake-fixer.zip -d .agents/skills
Documentation by qlqlmi
Cypress Flake Fixer
Audit an existing Cypress suite for the code patterns that cause intermittent failures, then fix them without hiding the problem behind retries, longer timeouts, or force: true.
When to Use This Skill
A Cypress spec passes locally and fails in CI, or fails once in every few runs
The suite contains
cy.wait(<number>),{ force: true }, or tests that only pass in orderErrors mention "detached from the DOM", "timed out retrying", or a subject that "is no longer attached"
The project is upgrading Cypress across a major version (12 through 16)
A review of Cypress test code is requested
For writing new Cypress tests from scratch, coding standards are enough. This skill is for diagnosing and repairing an existing suite.
Prerequisites
Node.js 18 or later to run the scanner (it has no dependencies and does not need Cypress installed)
The Cypress version, read from
package.json. Fixes differ by major version
Workflow
1. Scan
node ./scripts/scan-cypress.mjs <project-root>
node ./scripts/scan-cypress.mjs <project-root> --json # machine-readable
node ./scripts/scan-cypress.mjs <project-root> --strict # add low-confidence rules
node ./scripts/scan-cypress.mjs cypress/e2e/checkout.cy.ts # one fileThe scanner reads the Cypress version from the nearest package.json and grades removed APIs as error when the installed major already rejects them and warn when they break on upgrade. Run --list-rules for the catalog.
Findings are heuristic. Open each location and confirm before editing.
2. Measure before changing anything
When the goal is to fix a specific flaky spec, record how often it fails first. Without a baseline there is no way to tell a fix from luck.
for i in $(seq 1 20); do npx cypress run --spec "cypress/e2e/checkout.cy.ts" --quiet || echo "FAIL $i"; doneA spec that fails 1 run in 10 needs about 30 clean runs after the fix before the fix is believable.
3. Fix in this order
| Order | Rules | Why first |
|---|---|---|
| 1 | CY002, CY003, CY007 graded error | The test is wrong or already broken; other fixes build on correct command flow |
| 2 | CY001, intercept ordering | Time-based waits are the largest single source of flake |
| 3 | CY005, CY006 | Broken retry-ability causes detached-DOM and one-shot assertion failures |
| 4 | CY004 | force: true hides a real overlap, animation, or disabled state |
| 5 | CY008, CY010, CY012 | State leaks and order dependence |
| 6 | CY013, CY101, CY102 | Selector and assertion hygiene |
Before-and-after code for every rule is in references/anti-patterns.md. Replacements for removed APIs are in references/removed-apis.md. Read the section for the rule being fixed; do not load both files upfront.
4. Replace each fixed wait with the condition it was standing in for
Do not delete a cy.wait(n) or swap it for a guess. Work out what the delay covered:
| The wait covered | Replace with |
|---|---|
| A network request | cy.intercept(...).as('x') registered before the trigger, then cy.wait('@x') |
| A render that follows a request or state change | A .should() on the DOM that results |
| A debounce, throttle, polling interval, or toast timeout | cy.clock() before cy.visit(), then cy.tick(ms) |
| A CSS animation or transition | An assertion on the final state; Cypress already waits for the element to stop moving before acting |
| Client-side hydration of server-rendered HTML | A signal the app sets when hydration finishes (see Gotchas) |
| Unknown | Run the test in npx cypress open, select the wait in the Command Log, and read which requests and DOM changes happened during it |
5. Verify
Run the changed spec alone, then repeat it at least as many times as the baseline run.
Rerun the scanner and compare counts per rule.
Run the full suite once to catch order dependence exposed by the change.
Rules for the fix itself
Change test code only. If the test exposes an application bug (double submit, missing loading state, race in the UI), report it instead of working around it.
Do not raise
defaultCommandTimeout, addretries, or add{ force: true }to make a test pass. Each one converts a visible failure into a slower or hidden one.Do not replace
cy.wait(2000)withcy.wait(5000), or with.should('exist')on an element that was already present.Keep one rule category per commit so a regression can be bisected.
Fix shared custom commands in
cypress/supportfirst. A fixed wait inside a command runs in every test that calls it.
Gotchas
Register
cy.intercept()before the request can fire. For requests made on page load that means beforecy.visit(). An intercept registered after the request has left never matches, andcy.wait('@alias')times out intermittently depending on network speed.Each
cy.wait('@alias')consumes one request. If the app calls the endpoint twice, the first wait resolves on the first call and the assertion runs against stale data. Wait once per expected call, or assert on the DOM.GraphQL uses one URL for every operation. Alias inside the handler:
cy.intercept('POST', '/graphql', (req) => { if (req.body.operationName === 'GetOrders') req.alias = 'getOrders' })..should('not.exist')passes before the element has rendered. Using it to wait for a spinner to disappear succeeds instantly on a slow page. Assert the positive end state.Server-rendered apps accept clicks before handlers are attached. In Next.js, Nuxt, SvelteKit, and Remix the button is visible and enabled in the server HTML, so Cypress clicks it during hydration and nothing happens. Have the app set a marker when hydration completes (for example a
data-hydratedattribute on<body>from a mount effect) and assert on it aftercy.visit().A
.should()in the middle of a chain pins the subject. Queries after it cannot re-query past the assertion, so a re-render produces a detached-DOM error. Split the chain at the assertion..then()breaks the retry chain even with no assertion inside. Everything before it runs once.Cypress 16 types with no delay between keys (
keystrokeDelaydefault changed from 10 to 0). Inputs that re-render per keystroke or debounce on input may now drop characters or fire once. Assert the field value after typing instead of restoring the delay.Cypress 16 turned cookie and storage getters into queries.
cy.getCookie(),cy.getCookies(),cy.getAllCookies(),cy.getAllLocalStorage(), andcy.getAllSessionStorage()now retry chained.should()assertions, which removes the need for waits around auth cookies.The page is blank after
cy.session(). A missingcy.visit()after it looks like a flaky selector failure.testIsolation: falseshares state across tests. If the config sets it, every order-dependent failure is expected behavior, not flake. Check the config before diagnosing.Retries hide flake unless configured to report it. To find flaky tests instead of masking them, use the experimental strategy that retries and still fails:
retries: { experimentalStrategy: 'detect-flake-but-always-fail', experimentalOptions: { maxRetries: 2, stopIfAnyPassed: true }, openMode: true, runMode: true, }CY005 is a judgement call.
cy.get(input).clear().type('x')on an input that never re-renders is fine. Split the chain when the element belongs to a list, a form library that remounts fields, or anything driven by async state.
Report format
## Cypress flake audit: <scope>
- Cypress version: <range>, major <n>
- Files scanned: <n>
- Baseline: <spec> failed <f> of <n> runs
| Rule | Before | After | Notes |
|---|---|---|---|
| CY001 fixed-wait | 14 | 0 | 9 replaced by intercept aliases, 5 by assertions |
### Not fixed
- <location>: <reason, for example needs an application change>
### Application issues found
- <behavior the tests exposed>
### Verification
- <spec>: <n> of <n> runs passed after the changeTroubleshooting
| Issue | Solution |
|---|---|
| Scanner reports "No Cypress files found" | Pass the folder that contains cypress/ or *.cy.* files. Specs outside those conventions can be passed as explicit file paths |
| A finding is a false positive | Add // cy-scan-ignore CY0xx on the same or previous line, with the reason |
| Version shows "not detected" | Pass --cypress-major <n>; in a monorepo, run the scanner from the package that depends on Cypress |
| The test fails only in CI after fixes | Compare viewport, browser, and CPU. Run locally with the CI browser and --browser chrome --headless, and throttle CPU to surface timing gaps |
cy.wait('@alias') times out after the change | The intercept is registered after the request, the URL pattern misses a query string (add *), or the request is served from cache and never reaches the network |
References
references/anti-patterns.md: before-and-after code for every scanner rule
references/removed-apis.md: removed APIs by Cypress major, with migration code for
Cypress.env()andcy.exec()
Files
- ATTRIBUTION.mdAdded by AutoGineer867 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md9.9 KiB
- references/anti-patterns.md8.6 KiB
- references/removed-apis.md7.1 KiB
- scripts/scan-cypress.mjsScript22.7 KiB
references/removed-apis.md
Cypress APIs removed or changed, by major version
The scanner reports these as CY007. An entry is graded error when the installed major already rejects it. Always confirm against the official migration guide for the exact target version.
Cypress 16
Requires Node.js 22, 24, or 26+.
| Removed or changed | Replacement |
|---|---|
Cypress.env() | cy.env([...]) for secrets, Cypress.expose() for public values |
env in a test or suite config object | expose |
allowCypressEnv config option | delete |
cy.exec(), execTimeout | cy.task() in setupNodeEvents, taskTimeout |
.end() | delete the call |
cy.getCookie(), cy.getCookies(), cy.getAllCookies(), cy.getAllLocalStorage(), cy.getAllSessionStorage() | now queries: chain .should(); override with Cypress.Commands.overwriteQuery() |
Cypress.config('viewportWidth' / 'viewportHeight' / 'blockHosts', v) during a test | cy.viewport(w, h); { blockHosts: '...' } in the test config object |
experimentalMemoryManagement: true | delete (on by default as manageBrowserMemory) |
experimentalMemoryManagement: false | manageBrowserMemory: false |
experimentalFastVisibility | delete; visibilityStrategy defaults to 'modern' |
experimentalSourceRewriting | delete; removeSRIAttributes if it was used for SRI errors |
keystrokeDelay default 10 | default is 0; pass { delay: 10 } to a single .type() only where the app needs it |
| CoffeeScript specs, support files, fixtures | convert to JavaScript or TypeScript |
cypress/angular-zoneless | cypress/angular |
| Electron as the test browser | deprecated: set defaultBrowser: 'chrome' or pass --browser chrome |
Component testing minimums in 16: Angular 21, Vite 8, Next.js 15.0.4.
Migrating Cypress.env()
Decide per key whether the value is sensitive.
Public values (feature flags, API version, public URLs) are a mechanical change, because Cypress.expose() is synchronous like the API it replaces:
// cypress.config.js
module.exports = defineConfig({
expose: { apiVersion: 'v2', featureNewCheckout: true }, // moved out of env
env: { apiKey: process.env.API_KEY }, // secrets stay in env
})
// Before
const version = Cypress.env('apiVersion')
// After
const version = Cypress.expose('apiVersion')CLI:
--env apiVersion=v2becomes--expose apiVersion=v2(short form-x).Per test:
it('...', { env: { flag: true } }, ...)becomes{ expose: { flag: true } }.CYPRESS_*environment variables populateenv, notexpose. A public value that CI injects asCYPRESS_apiVersionmust be either read withcy.env()or copied intoexposein the config file (expose: { apiVersion: process.env.API_VERSION }).
Sensitive values require restructuring, because cy.env() is an asynchronous command:
// Before: read at module scope, used anywhere
const apiKey = Cypress.env('apiKey')
it('lists users', () => {
cy.request({ url: '/api/users', headers: { Authorization: `Bearer ${apiKey}` } })
})
// After: read inside the test, used inside the callback
it('lists users', () => {
cy.env(['apiKey']).then(({ apiKey }) => {
cy.request({ url: '/api/users', headers: { Authorization: `Bearer ${apiKey}` } })
})
})cy.env()takes an array of keys and yields an object. An undefined key yieldsundefined.It cannot be called at module scope or outside a test or hook.
It cannot set values. Code that used
Cypress.env('token', value)to pass state between steps should use an alias within a test, or aset/getpair of tasks across tests.Yielded values are not masked. Do not assert on them or pass them through
.its().Inside
cy.origin(), callcy.env()within the callback.
Plugins that call Cypress.env() throw on Cypress 16. Upgrade them in the same change. Known minimums: @cypress/grep 6.0.0, @cypress/code-coverage 4.0.0, cypress-mailpit 2.0.0. Search node_modules of other Cypress plugins for Cypress.env( before upgrading.
On Cypress 15.10 through 15.x, set allowCypressEnv: false after migrating to make any remaining Cypress.env() call fail early. Remove the option when moving to 16.
Migrating cy.exec()
// cypress.config.js
const { execFileSync } = require('node:child_process')
module.exports = defineConfig({
e2e: {
setupNodeEvents(on) {
on('task', {
seedDatabase(fixture) {
execFileSync('node', ['scripts/seed.js', fixture], { stdio: 'inherit' })
return null
},
})
},
},
})
// Before
cy.exec('node scripts/seed.js users')
// After
cy.task('seedDatabase', 'users')A task must return a value or
null. Returningundefinedfails the task.Use
execFileSyncwith an argument array so test input never reaches a shell.Tasks time out after 60 seconds by default; set
taskTimeoutfor longer work.
Cypress 15
Requires Node.js 20, 22, or 24+ (18 and 23 dropped).
| Removed or changed | Replacement |
|---|---|
cy.stub(obj, 'method', fn) | cy.stub(obj, 'method').callsFake(fn) |
cy.exec(...).its('code') | exitCode |
Cypress.SelectorPlayground | Cypress.ElementSelector |
| Webpack 4 | Webpack 5 |
| Firefox automation over CDP | WebDriver BiDi only; Firefox 135+ (140+ from 15.19) |
CommonJS config with @cypress/vite-dev-server | ESM config (.mjs, "type": "module", or cypress.config.ts) |
Cypress 14
| Removed or changed | Replacement |
|---|---|
Commands on a different subdomain worked without cy.origin() | wrap them in cy.origin(); injectDocumentDomain is a deprecated escape hatch |
experimentalSkipDomainInjection | removed |
experimentalJustInTimeCompile | justInTimeCompile |
Cypress 13
| Removed or changed | Replacement |
|---|---|
video default true | default false; enable explicitly if CI relies on videos |
videoUploadOnPasses | removed |
Cypress 12
| Removed or changed | Replacement |
|---|---|
cy.server(), cy.route() | cy.intercept() |
Cypress.Cookies.preserveOnce(), Cypress.Cookies.defaults() | cy.session() |
experimentalSessionAndOrigin | delete; cy.session() and cy.origin() are stable |
| Tests shared page and storage state | testIsolation is on: each test starts on a blank page with cleared cookies and storage |
cy.route() to cy.intercept() is not a rename. Differences that change test behavior:
cy.intercept()glob-matches the full URL including the query string.cy.intercept('/api/users')never matches/api/users?page=2; use'/api/users*'or{ pathname: '/api/users' }.cy.intercept()matches every HTTP method when none is given.cy.route()defaulted toGET.When several intercepts match, the most recently defined one runs first. Define general stubs in
beforeEachand overrides inside the test.A response served from the browser cache never reaches the network layer, so the intercept does not fire and
cy.wait('@alias')times out. Disable cache headers on the test server.cy.intercept()also seesfetchrequests and static resources, whichcy.route()did not.
Requirements and compatibility
Written for: GitHub Copilot
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs Node.js
Security
What our scanner noticed· Low risk
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- First committed by
qlqlmi
- Publisher
- GitHub (Official)
- Distributed by
- GitHub
- Source
- github/awesome-copilot · skills/cypress-flake-fixer · commit 797337f
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
- Contributors
- qlqlmi
AutoGineer is not affiliated with or endorsed by qlqlmi or GitHub.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download cypress-flake-fixer.zip