Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Use cy.get() to find a stable set of test elements, then choose a random index inside the query’s .then() callback and act on that indexed result. Cypress does not provide a dedicated random-element command; the selection is ordinary JavaScript applied to Cypress’s yielded collection. Record the index when a failure needs to be reproduced, and query again after actions that may re-render the page.

Randomly select one element from a Cypress query

Give the intended candidates a test-specific attribute, query them with cy.get(), and select an index from the yielded collection. For example, if each menu option has data-cy="menu-item":

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 up to, but not including, 1. Multiplying by the collection length and applying Math.floor() produces an integer from 0 through $items.length - 1. Cypress documents cy.get() as a query that yields matching DOM elements, and .eq(index) as the way to select an element at a given index from the result (Cypress cy.get() documentation).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The callback matters: Cypress commands are queued and run serially, so the query must yield its collection before the JavaScript can calculate a valid index. Wrapping the indexed jQuery element with cy.wrap() puts it back into the Cypress command chain so .click() runs as a Cypress action. Do not calculate an index before the query has produced its collection.

Make an empty collection fail clearly

The compact example assumes that the query finds at least one matching element. If an empty candidate set should produce an explicit assertion failure, assert that before choosing:

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() retries while looking for matching elements, and Cypress retries chained assertions as documented. The length assertion makes the non-empty requirement visible in the test rather than allowing a random-index calculation against an empty collection. If the assertion fails, inspect whether the selector is correct, whether the elements should exist at that point in the test, and whether the page has finished rendering them.

Choose selectors that identify the intended candidates

Randomness is only useful if the query selects the right set. Prefer a dedicated testing attribute such as data-cy over selectors tied to visual styling or application behavior. Cypress recommends test-specific data-* attributes because they are decoupled from CSS and JavaScript changes (Cypress best practices).

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Keep the selector narrow enough that every match is a valid candidate for the action. If the page has several menus, scope the selection to the relevant container before choosing; otherwise a random index can select an element from the wrong region. Conversely, do not make the selector depend on a fragile class merely to reduce the result count. Prefer improving the test markup so it describes the candidate set clearly.

Before adding randomness, confirm that a random choice is actually the test’s goal. Randomly clicking a menu item can vary the interaction under test, but it does not ensure that each menu item is exercised in any particular run. If every candidate must be checked, use deterministic coverage—such as focused tests for individual cases—instead of assuming random runs will eventually find every issue.

Make random failures reproducible

A randomly selected element can expose an interaction path that a fixed choice misses, but an unexplained random failure is harder to debug. Preserve the chosen index in the test output or in a project-level test utility, and record enough context to reconstruct the candidate collection for that run. A simple console message makes the chosen position visible:

cy.get('[data-cy="menu-item"]')
  .should('have.length.greaterThan', 0)
  .then(($items) => {
    const index = Math.floor(Math.random() * $items.length)
    console.log('Randomly selected menu item index:', index)
    cy.wrap($items.eq(index)).click()
  })

An index only reproduces the same element if the candidate ordering and collection are the same. If items are inserted, removed, or reordered between runs, capture or otherwise inspect the candidate list as well. For a project that needs repeatable random sequences, use a controllable seed or random source in its own test utilities; the random-index expression above is not a Cypress-specific seeded-random feature.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Cypress describes its purpose as creating consistent, non-flaky tests that perform identically each time they run (Introduction to Cypress). Random selection deliberately introduces variation, so keep it scoped to the behavior where variation adds value. When investigating a failure, switch to a known index or otherwise make the choice repeatable before changing the underlying test or application code.

Handle page re-renders without stale elements

The random callback works with the elements yielded by that query. If clicking one candidate changes the page or causes the relevant area to re-render, do not keep acting on an old element reference for a later step. Query the current DOM again before the next action, then apply the selector and index logic to the newly yielded collection. That way the next selection is based on current elements instead of references from the previous render.

cy.each() is an iteration command, not a substitute random selector. It yields the original collection and does not retry assertions; Cypress’s documentation advises re-querying when an action can make the subject stale (Cypress cy.each() documentation). Use iteration when you intend to process each item, not when the test should pick exactly one. If the UI changes as each item is processed, structure the test to query again at the point each current element is needed.

Choose random or exhaustive selection deliberately

Approach What one run covers Reproducing a failure Best fit
Random index One selected candidate Record the index and, if ordering can change, the candidate context Varying an interaction where any one of several equivalent candidates is appropriate
Deterministic selection The explicitly selected candidate or candidates in that test Repeat the same path by rerunning the same test Verifying a specific item or requiring a predictable reproduction
Exhaustive coverage Each candidate, when tests are designed to cover them all Failures point to a specific candidate or test case Requirements that every option must work on every test run

Random selection changes which candidate is exercised; it does not turn a one-candidate test into exhaustive coverage. Cypress’s serial command queue supports a repeatable command model, so keep the random decision explicit and diagnosable rather than scattering random calls throughout a test (Introduction to Cypress).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Troubleshoot common failures

  • The test reports an empty or invalid selection. Check the data-cy value and confirm the elements should exist when the query runs. Add the positive-length assertion when an empty set is a test failure, and ensure the selector matches only intended candidates.
  • The random index is outside the expected range. Calculate it from the yielded collection’s current length using Math.floor(Math.random() * $items.length). Do not hard-code a maximum based on a collection that may change.
  • The click fails after an earlier action. The earlier action may have re-rendered the relevant DOM. Run a fresh cy.get() query before selecting and acting on the next element rather than relying on a stale reference.
  • A failure is difficult to reproduce. Log or otherwise preserve the selected index and inspect the candidate ordering. Make the choice deterministic while debugging, or use a controllable random source in project test utilities if repeatable sequences are needed.
  • The test passes but some candidates are never tested. That is expected from a random single-element choice: each execution selects one candidate, not all of them. Use explicit deterministic cases or an exhaustive test design for per-candidate guarantees.
  • Every item is acted on despite wanting one. Check that the test is not using .each() for selection. Iteration visits collection members; choose an index and wrap only that result for a single random action.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

ScreenshotNeo is a separate website screenshot API, not a way to randomize Cypress element selection. If you also need a clean screenshot of a page involved in your test workflow, one GET request can return an image or PDF; see the ScreenshotNeo API documentation for parameters.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

ScreenshotNeo accepts cookie or consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each of those steps can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Every feature is available on every plan.

Sign up for ScreenshotNeo’s free plan: 1,000 screenshots a month, no card required.

Frequently Asked Questions

Does Cypress have a built-in random-element command?

No dedicated random-element command is established in the cited Cypress documentation. The selection pattern uses ordinary JavaScript to choose an index from the collection yielded by Cypress.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Is Math.random() suitable for security-sensitive randomness?

No. The example uses Math.random() only to vary a test interaction; it is not a cryptographic random-number method.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.