How to Randomize Element Selection in Cypress Tests
Select a random Cypress element reliably, make failures reproducible, handle re-renders, and know when deterministic coverage is the better choice.

To randomize an element in Cypress, query a stable selector, choose an index inside the yielded collection, and wrap that element before acting:
cy.get('[data-cy="menu-item"]').then(($items) => {
const index = Math.floor(Math.random() * $items.length)
cy.wrap($items.eq(index)).click()
})
cy.get() yields matching elements and retries until the query succeeds; .eq(index) selects one item from that result. Cypress commands are queued and run serially, so make the random choice inside the callback that receives the query result. See the official cy.get() and Cypress introduction documentation.
1. Use a stable candidate selector
Give the elements you may select a test-specific attribute such as data-cy:
<nav>
<a data-cy="menu-item" href="/docs">Docs</a>
<a data-cy="menu-item" href="/pricing">Pricing</a>
<a data-cy="menu-item" href="/contact">Contact</a>
</nav>
Cypress recommends dedicated data-* selectors because they are decoupled from CSS classes and JavaScript behavior. A class such as .card may change during a redesign; a test attribute communicates that the element is part of the test contract. Read the Cypress best practices.
2. Select a random element safely
Basic selection
cy.get('[data-cy="menu-item"]').then(($items) => {
const index = Math.floor(Math.random() * $items.length)
cy.wrap($items.eq(index)).click()
})
Math.random() returns a value from 0 (inclusive) to 1 (exclusive). Multiplying by the collection length and flooring it produces an integer from 0 through length - 1.

Fail clearly when there are no candidates
cy.get('[data-cy="menu-item"]')
.should('have.length.greaterThan', 0)
.then(($items) => {
const index = Math.floor(Math.random() * $items.length)
cy.wrap($items.eq(index)).click()
})
The assertion gives a useful diagnostic instead of allowing an empty collection to produce an invalid selection.
Log the choice for debugging
cy.get('[data-cy="menu-item"]')
.should('have.length.greaterThan', 0)
.then(($items) => {
const index = Math.floor(Math.random() * $items.length)
cy.log(`Selected menu item ${index + 1} of ${$items.length}`)
cy.wrap($items.eq(index)).click()
})
Also record the index in your CI output or failure artifact. A random test is only useful when a failed run can be replayed.
3. Make random failures reproducible
Uncontrolled randomness changes the input on every run. Use a seed or an injectable random function in a project utility, and print the seed before selecting.
function seededRandom(seed) {
let value = seed >>> 0
return () => {
value = (value * 1664525 + 1013904223) % 4294967296
return value / 4294967296
}
}
const seed = Number(Cypress.env('RANDOM_SEED') || Date.now())
const random = seededRandom(seed)
cy.log(`Random seed: ${seed}`)
cy.get('[data-cy="menu-item"]')
.should('have.length.greaterThan', 0)
.then(($items) => {
const index = Math.floor(random() * $items.length)
cy.log(`Selected index: ${index}`)
cy.wrap($items.eq(index)).click()
})
To replay a failure, run Cypress with the same RANDOM_SEED value. The seeded helper is ordinary JavaScript; Cypress does not provide a dedicated random-element command.
4. Re-query after actions that re-render the page
The jQuery collection yielded by cy.get() is a snapshot. If clicking an item replaces the list, do not keep using that old collection. Query again after the state change:

cy.get('[data-cy="menu-item"]')
.should('have.length.greaterThan', 0)
.then(($items) => {
const index = Math.floor(Math.random() * $items.length)
cy.wrap($items.eq(index)).click()
})
cy.get('[data-cy="result"]')
.should('be.visible')
If a later action targets another menu item after a render, call cy.get('[data-cy="menu-item"]') again rather than reusing $items.
5. Random selection versus exhaustive coverage
| Goal | Approach | Trade-off |
|---|---|---|
| Vary one interaction per run | Random index | Different candidates are exercised over many runs, but one run covers only one. |
| Verify every candidate on every run | Deterministic loop or separate test cases | Longer run time, predictable coverage. |
| Investigate a failure | Seeded random choice | Requires recording and restoring the seed. |
Randomization complements deterministic tests; it does not replace them. If every menu item must work, iterate deterministically and assert each result.
6. Why cy.each() is not a random selector
.each() iterates over the collection and yields the original subject. It is useful for checking every item, but it does not retry assertions and can become unsafe when an action re-renders the page. The official each() documentation explains these subject and retry rules.
cy.get('[data-cy="menu-item"]').each(($item) => {
cy.wrap($item).should('be.visible')
})
For a random action, choose one index in a .then() callback. For exhaustive checks, prefer a deterministic loop and re-query between page-changing actions.
7. Common errors and fixes
| Error | Cause | Fix |
|---|---|---|
Cannot read properties of undefined |
The candidate collection is empty or the index was calculated before the query yielded. | Assert a positive length and calculate the index inside .then(). |
| The test sometimes clicks the wrong element | Selectors depend on layout, classes, or changing text. | Add a stable data-cy attribute. |
Detached from the DOM |
The page re-rendered after the collection was captured. | Re-query immediately before the next action. |
| Failures cannot be reproduced | The random source is not recorded. | Log a seed and selected index; rerun with the same seed. |
Assertions inside each() behave unexpectedly |
each() does not retry assertions on the yielded item. |
Use a direct Cypress query or re-query inside the iteration. |
| Test passes while coverage is poor | Random choice visits only one candidate per execution. | Track candidate coverage separately and add deterministic tests for required paths. |
8. Performance and reliability notes
- Use the narrowest selector that defines the candidate set. Fewer matches make the intent clearer and reduce DOM work.
- Let Cypress retry the query and its assertions instead of adding arbitrary sleeps.
- Keep random selection in the Cypress command chain; do not mix it with immediate DOM reads outside Cypress commands.
- Run a deterministic smoke suite on every change, then use seeded random runs for broader interaction coverage.
- When parallelizing CI, include the seed, browser, viewport, and spec name in failure output so another worker can replay the same case.
9. Complete example
describe('random menu navigation', () => {
it('opens one menu item and shows its page', () => {
const seed = Number(Cypress.env('RANDOM_SEED') || Date.now())
let state = seed >>> 0
const random = () => {
state = (state * 1664525 + 1013904223) % 4294967296
return state / 4294967296
}
cy.visit('/menu')
cy.log(`Random seed: ${seed}`)
cy.get('[data-cy="menu-item"]')
.should('have.length.greaterThan', 0)
.then(($items) => {
const index = Math.floor(random() * $items.length)
cy.log(`Selected index: ${index}`)
cy.wrap($items.eq(index)).click()
})
cy.get('[data-cy="page-content"]').should('be.visible')
})
})
Or skip the browser setup
If you need screenshots of the resulting pages rather than a browser harness, ScreenshotNeo returns an image or PDF from one GET request. Its capture flow accepts cookie banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before the shot. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status.
Use the ScreenshotNeo API documentation for the complete option list, including selectors, waits, custom JavaScript, device presets, full-page capture, PDFs, caching, signed links, async jobs, and bulk capture.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
An MCP server also lets Claude, Cursor, and other MCP clients call take_screenshot, get_page_info, and capture_pdf. The Free plan includes 1,000 screenshots each month with no card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.
FAQ
Does Cypress have a random-element command?
No. Query with cy.get(), calculate an index with JavaScript, and select it with .eq().
Should I randomize the selector itself?
No. Keep the selector stable and randomize the index among its matched elements.
Can random selection prove all elements work?
No. It samples one candidate per run. Use deterministic exhaustive tests for complete coverage.
Where should I store the seed?
Log it with the test result and pass it through a Cypress environment variable so a failed run can be replayed.


