Cypress Flake Fixer

Cypress Flake Fixer

Guides an agent to scan a Cypress suite for flake-prone patterns and removed APIs, then fix them without retries or forced actions, with a bundled scanner script.

Skill files4 files

references/

scripts/

SKILL.md155 lines
1
---
2
name: cypress-flake-fixer
3
description: 'Find and fix flake-prone anti-patterns in an existing Cypress suite, and APIs removed in Cypress 12 to 16. Bundles a zero-dependency scanner for fixed cy.wait() delays, assigned command return values, async/await, force: true, chaining after actions, one-shot expect() inside .then(), conditional testing, and removed APIs such as Cypress.env(), cy.exec(), cy.server()/cy.route(). Use when asked to fix flaky Cypress tests, remove cy.wait, stabilize or harden a Cypress suite, audit Cypress specs, debug "detached from the DOM" errors, or prepare an upgrade to Cypress 15 or 16.'
4
---
5
6
# Cypress Flake Fixer
7
8
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`.
9
10
## When to Use This Skill
11
12
- A Cypress spec passes locally and fails in CI, or fails once in every few runs
13
- The suite contains `cy.wait(<number>)`, `{ force: true }`, or tests that only pass in order
14
- Errors mention "detached from the DOM", "timed out retrying", or a subject that "is no longer attached"
15
- The project is upgrading Cypress across a major version (12 through 16)
16
- A review of Cypress test code is requested
17
18
For writing new Cypress tests from scratch, coding standards are enough. This skill is for diagnosing and repairing an existing suite.
19
20
## Prerequisites
21
22
- Node.js 18 or later to run the scanner (it has no dependencies and does not need Cypress installed)
23
- The Cypress version, read from `package.json`. Fixes differ by major version
24
25
## Workflow
26
27
### 1. Scan
28
29
```bash
30
node ./scripts/scan-cypress.mjs <project-root>
31
node ./scripts/scan-cypress.mjs <project-root> --json # machine-readable
32
node ./scripts/scan-cypress.mjs <project-root> --strict # add low-confidence rules
33
node ./scripts/scan-cypress.mjs cypress/e2e/checkout.cy.ts # one file
34
```
35
36
The 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.
37
38
Findings are heuristic. Open each location and confirm before editing.
39
40
### 2. Measure before changing anything
41
42
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.
43
44
```bash
45
for i in $(seq 1 20); do npx cypress run --spec "cypress/e2e/checkout.cy.ts" --quiet || echo "FAIL $i"; done
46
```
47
48
A spec that fails 1 run in 10 needs about 30 clean runs after the fix before the fix is believable.
49
50
### 3. Fix in this order
51
52
| Order | Rules | Why first |
53
|---|---|---|
54
| 1 | CY002, CY003, CY007 graded `error` | The test is wrong or already broken; other fixes build on correct command flow |
55
| 2 | CY001, intercept ordering | Time-based waits are the largest single source of flake |
56
| 3 | CY005, CY006 | Broken retry-ability causes detached-DOM and one-shot assertion failures |
57
| 4 | CY004 | `force: true` hides a real overlap, animation, or disabled state |
58
| 5 | CY008, CY010, CY012 | State leaks and order dependence |
59
| 6 | CY013, CY101, CY102 | Selector and assertion hygiene |
60
61
Before-and-after code for every rule is in [references/anti-patterns.md](./references/anti-patterns.md). Replacements for removed APIs are in [references/removed-apis.md](./references/removed-apis.md). Read the section for the rule being fixed; do not load both files upfront.
62
63
### 4. Replace each fixed wait with the condition it was standing in for
64
65
Do not delete a `cy.wait(n)` or swap it for a guess. Work out what the delay covered:
66
67
| The wait covered | Replace with |
68
|---|---|
69
| A network request | `cy.intercept(...).as('x')` registered before the trigger, then `cy.wait('@x')` |
70
| A render that follows a request or state change | A `.should()` on the DOM that results |
71
| A debounce, throttle, polling interval, or toast timeout | `cy.clock()` before `cy.visit()`, then `cy.tick(ms)` |
72
| A CSS animation or transition | An assertion on the final state; Cypress already waits for the element to stop moving before acting |
73
| Client-side hydration of server-rendered HTML | A signal the app sets when hydration finishes (see Gotchas) |
74
| 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 |
75
76
### 5. Verify
77
78
1. Run the changed spec alone, then repeat it at least as many times as the baseline run.
79
2. Rerun the scanner and compare counts per rule.
80
3. Run the full suite once to catch order dependence exposed by the change.
81
82
## Rules for the fix itself
83
84
- 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.
85
- Do not raise `defaultCommandTimeout`, add `retries`, or add `{ force: true }` to make a test pass. Each one converts a visible failure into a slower or hidden one.
86
- Do not replace `cy.wait(2000)` with `cy.wait(5000)`, or with `.should('exist')` on an element that was already present.
87
- Keep one rule category per commit so a regression can be bisected.
88
- Fix shared custom commands in `cypress/support` first. A fixed wait inside a command runs in every test that calls it.
89
90
## Gotchas
91
92
- **Register `cy.intercept()` before the request can fire.** For requests made on page load that means before `cy.visit()`. An intercept registered after the request has left never matches, and `cy.wait('@alias')` times out intermittently depending on network speed.
93
- **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.
94
- **GraphQL uses one URL for every operation.** Alias inside the handler: `cy.intercept('POST', '/graphql', (req) => { if (req.body.operationName === 'GetOrders') req.alias = 'getOrders' })`.
95
- **`.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.
96
- **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-hydrated` attribute on `<body>` from a mount effect) and assert on it after `cy.visit()`.
97
- **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.
98
- **`.then()` breaks the retry chain even with no assertion inside.** Everything before it runs once.
99
- **Cypress 16 types with no delay between keys** (`keystrokeDelay` default 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.
100
- **Cypress 16 turned cookie and storage getters into queries.** `cy.getCookie()`, `cy.getCookies()`, `cy.getAllCookies()`, `cy.getAllLocalStorage()`, and `cy.getAllSessionStorage()` now retry chained `.should()` assertions, which removes the need for waits around auth cookies.
101
- **The page is blank after `cy.session()`.** A missing `cy.visit()` after it looks like a flaky selector failure.
102
- **`testIsolation: false` shares state across tests.** If the config sets it, every order-dependent failure is expected behavior, not flake. Check the config before diagnosing.
103
- **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:
104
105
```js
106
retries: {
107
experimentalStrategy: 'detect-flake-but-always-fail',
108
experimentalOptions: { maxRetries: 2, stopIfAnyPassed: true },
109
openMode: true,
110
runMode: true,
111
}
112
```
113
114
- **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.
115
116
## Report format
117
118
```markdown
119
## Cypress flake audit: <scope>
120
121
- Cypress version: <range>, major <n>
122
- Files scanned: <n>
123
- Baseline: <spec> failed <f> of <n> runs
124
125
| Rule | Before | After | Notes |
126
|---|---|---|---|
127
| CY001 fixed-wait | 14 | 0 | 9 replaced by intercept aliases, 5 by assertions |
128
129
### Not fixed
130
- <location>: <reason, for example needs an application change>
131
132
### Application issues found
133
- <behavior the tests exposed>
134
135
### Verification
136
- <spec>: <n> of <n> runs passed after the change
137
```
138
139
## Troubleshooting
140
141
| Issue | Solution |
142
|---|---|
143
| 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 |
144
| A finding is a false positive | Add `// cy-scan-ignore CY0xx` on the same or previous line, with the reason |
145
| Version shows "not detected" | Pass `--cypress-major <n>`; in a monorepo, run the scanner from the package that depends on Cypress |
146
| 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 |
147
| `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 |
148
149
## References
150
151
- [references/anti-patterns.md](./references/anti-patterns.md): before-and-after code for every scanner rule
152
- [references/removed-apis.md](./references/removed-apis.md): removed APIs by Cypress major, with migration code for `Cypress.env()` and `cy.exec()`
153
- [Cypress retry-ability](https://docs.cypress.io/app/core-concepts/retry-ability)
154
- [Cypress migration guide](https://docs.cypress.io/app/references/migration-guide)
155

© GitHub, Inc. · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

1 view
Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…