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.

Anchor the query to the element that gives the test meaning. Use .find() when the icon is inside that element; use .closest() to reach a shared row or card first when the icon and the identifying text are siblings. Then assert the property that matters, such as visibility, an attribute, a class, or count.

The two Cypress query patterns you need

The correct command follows the DOM relationship, not the visual position of the icon on the page. Cypress queries are retryable, so a chained query and assertion can wait for the application to render the expected element.

Icon is a descendant of the anchor element

Start with a meaningful control or container, then call .find(). It searches descendants of the current Cypress subject.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
cy.contains('button', 'Save')
  .find('svg[data-cy="save-icon"]')
  .should('be.visible')

This works for an SVG nested directly in a button, or several levels deeper inside the button. Replace the example selector with one from your actual markup.

#1 Best Overall
Amazon Basics Wired QWERTY Keyboard, Works with Windows, Plug and Play, Easy to Use with Media Control, Full-Sized, Black
  • KEYBOARD: The keyboard works for Windows with hot keys that enable easy access to Media, My Computer, Mute, Volume up/down, and Calculator
  • EASY SETUP: Experience simple installation with the USB wired connection
  • VERSATILE COMPATIBILITY: This keyboard is designed to work with multiple Windows versions, including Vista, 7, 8, 10 offering broad compatibility across devices.
  • SLEEK DESIGN: The elegant black color of the wired keyboard complements your tech and decor, adding a stylish and cohesive look to any setup without sacrificing function.
  • FULL-SIZED CONVENIENCE: The standard QWERTY layout of this keyboard set offers a familiar typing experience, ideal for both professional tasks and personal use.

Icon and text share a row or card

When the text identifies a row but the icon is a sibling elsewhere in that row, first climb to the shared container with .closest(), then narrow back down with .find().

cy.get('[data-cy="product-row"]')
  .contains('Product name')
  .closest('[data-cy="product-row"]')
  .find('[data-cy="status-icon"]')
  .should('be.visible')

.closest() returns the subject itself if it matches, or the first matching ancestor. That makes it useful when the text may be wrapped in a heading, link, or nested label.

The icon is the interactive control

An icon-only button should be tested as a named button, not as a decorative SVG. The control needs an accessible name, normally supplied by aria-label or visible text.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
cy.get('button[aria-label="Close"]')
  .should('be.visible')
  .click()

Use a descendant SVG selector only when the test is specifically about rendering details, such as whether the expected icon is present inside an already identified button.

Choose a stable anchor before writing the chain

Prefer user meaning or a test attribute

Begin with a label, role, or stable attribute that explains what the element does. A data-cy attribute is usually less brittle than a generated class name. User-visible text can be appropriate when the text is part of the behavior under test.

Rank #2
Sale
Logitech MK270 Full Size Wireless Keyboard and Mouse Combo - Black
  • Reliable Plug and Play: The USB receiver provides a reliable wireless connection up to 33 ft (1), so you can forget about drop-outs and delays and you can take it wherever you use your computer
  • Type in Comfort: The design of this keyboard creates a comfortable typing experience thanks to the low-profile, quiet keys and standard layout with full-size F-keys, number pad, and arrow keys
  • Durable and Resilient: This full-size wireless keyboard features a spill-resistant design (2), durable keys and sturdy tilt legs with adjustable height
  • Long Battery Life: MK270 combo features a 36-month keyboard and 12-month mouse battery life (3), along with on/off switches allowing you to go months without the hassle of changing batteries
  • Easy to Use: This wireless keyboard and mouse combo features 8 multimedia hotkeys for instant access to the Internet, email, play/pause, and volume so you can easily check out your favorite sites
cy.contains('[data-cy="item-row"]', 'Invoice 104')
  .find('[data-cy="warning-icon"]')
  .should('have.attr', 'aria-hidden', 'true')

The selector argument limits cy.contains() to matching elements, while the text identifies the intended item. If your application is localized, avoid relying on a language-specific string unless the test is intentionally validating that translation.

Match the real container

Use the nearest semantic container that owns both the identifying element and the icon. Typical containers are a table row, list item, card, form field, or toolbar group.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
cy.contains('h2', 'Profile')
  .closest('[data-cy="profile-card"]')
  .find('svg[data-cy="edit-icon"]')
  .should('exist')

Do not climb to a broad page wrapper merely because it is convenient. A broad ancestor can contain several identical icons and make the test pass for the wrong item.

Use .within() when several assertions share one scope

.within() changes the root for commands such as cy.get(). This is useful when you need to check a row’s label, icon, and action without repeating the row selector.

cy.get('[data-cy="product-row"]')
  .contains('Product name')
  .closest('[data-cy="product-row"]')
  .within(() => {
    cy.get('[data-cy="status-icon"]').should('be.visible')
    cy.get('button[aria-label="Open product"]').should('be.enabled')
  })

Inside the callback, cy.get() is scoped to the selected row. Outside it, cy.get() normally starts at the document, whereas .find() remains anchored to its current subject.

Rank #3
Sale
Logitech K120 Full Size Wired Keyboard USB Plug-and-Play Windows - Black
  • All-day Comfort: The design of this standard keyboard creates a comfortable typing experience thanks to the deep-profile keys and full-size standard layout with F-keys and number pad
  • Easy to Set-up and Use: Set-up couldn't be easier, you simply plug in this corded keyboard via USB on your desktop or laptop and start using right away without any software installation
  • Compatibility: This full-size keyboard is compatible with Windows 7, 8, 10 or later, plus it's a reliable and durable partner for your desk at home, or at work
  • Spill-proof: This durable keyboard features a spill-resistant design (1), anti-fade keys and sturdy tilt legs with adjustable height, meaning this keyboard is built to last
  • Plastic parts in K120 include 51% certified post-consumer recycled plastic*

Complete markup-and-test examples

Nested icon in a labeled button

Given markup like this:

<button data-cy="save-button" type="submit">
  <span>Save</span>
  <svg data-cy="save-icon" aria-hidden="true">...</svg>
</button>

Anchor on the button and find its icon:

cy.get('[data-cy="save-button"]')
  .find('svg[data-cy="save-icon"]')
  .should('exist')
  .and('be.visible')

Status icon in a repeated list

For a list where each row contains a product name and status icon:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<li data-cy="item-row">
  <a href="/invoices/104">Invoice 104</a>
  <svg data-cy="warning-icon" aria-hidden="true">...</svg>
</li>

Identify the row by its content, then search only inside that row:

cy.contains('[data-cy="item-row"]', 'Invoice 104')
  .find('[data-cy="warning-icon"]')
  .should('have.attr', 'aria-hidden', 'true')

This prevents a warning icon in another row from satisfying the assertion.

Text nested inside a card

If the title is deeply nested but the edit icon is elsewhere in the card, climb to the card boundary:

cy.contains('h2', 'Profile')
  .closest('[data-cy="profile-card"]')
  .find('svg[data-cy="edit-icon"]')
  .should('exist')

Testing the behavior instead of the SVG

When clicking an icon-only control, select the named control and assert the resulting behavior. This keeps the test aligned with what a user operates.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Redragon K521 Upgrade Rainbow LED Gaming Keyboard, 104 Keys Wired Mechanical Feeling Keyboard with Multimedia Keys, One-Touch Backlit, Anti-Ghosting, Compatible with PC, Mac, PS4/5, Xbox
  • 【Dreamy Rainbow Gaming Keyboard】K521 Gaming Keyboard Adopts a Different LED Backlight Design, Upgraded on the Traditional LED Backlight Effect, Making the Light More Penetrating, Giving You a More Dazzling Visual Effect, Making Your Gaming Process More Enjoyable
  • 【One Touch Opens & Visual Feast】The K521 Red Dragon Keyboard has a One-Touch on/off Lighting Button for Added Convenience. It also has a Three-Position Adjustable Breathing Mode and a Four-Position Adjustable Brightness Lighting Mode
  • 【Mechanical Feeling & Fast Tapping】The PC Keyboard Keys are Designed for Mechanical Feeling, Giving You a Better Feel During Use and the Ability to Trigger Keys Quickly, Allowing You to Win All Your Games
  • 【19 Keys Anti-Ghosting Keyboard】Anti-Ghosting Ensures Every Button Can Be Triggered. This Allows You to Trigger Key Combinations In The Game Accurately, And Each Skill Can Be Accurately Released to Increase Your Winning Rate. Redragon K521 Will Be Your Perfect Partner
  • 【12 Multimedia Combination Keys】The K521 Wired Gaming Keyboard is Equipped with 12 Multimedia Keys That Can Greatly Enhance Your Gaming/Office Efficiency and Make It More Convenient to Use
cy.get('button[aria-label="Close"]')
  .should('be.visible')
  .click()

cy.get('[data-cy="dialog"]').should('not.exist')

If the SVG itself is decorative, checking its path data or exact geometry usually adds maintenance without proving the user outcome. Test those details only when rendering the specific icon is the requirement.

Assertions that express the actual requirement

After locating the icon, choose an assertion that states what must be true:

  • should('exist') verifies that the matching element is in the DOM.
  • should('be.visible') verifies that it is rendered visibly.
  • should('have.attr', 'aria-hidden', 'true') checks an accessibility-related attribute.
  • should('have.class', 'is-warning') checks a state class when that class is part of the contract.
  • should('have.length', 1) detects an unexpectedly broad selector.

Queries and chained assertions retry while Cypress waits for the page to reach the requested state. Keep the query chain intact instead of extracting a DOM node synchronously and inspecting it outside Cypress’s command queue.

Common mistakes and their fixes

Symptom Likely cause Fix
.find() returns nothing The icon is not a descendant of the current subject. Inspect the markup. If text and icon are siblings, call .closest(container) before .find(icon).
The test finds an icon in the wrong card The chain starts from cy.get() at the document or uses an ancestor that is too broad. Identify the row or card with cy.contains(container, text), then search only within that subject.
Several icons match The selector is generic, such as svg, or the container is not unique. Add a stable data-cy attribute, a specific accessible label, or assert the expected count.
The test is flaky during loading A synchronous DOM read runs before the application finishes rendering. Use a retryable Cypress query followed by the assertion that describes the ready state.
Text-based lookup fails in another locale The visible label changes with translation. Use a stable test attribute or another locale-independent contract; reserve text matching for tests that intentionally verify translated content.
An icon-only button cannot be located reliably The control has no accessible name or the test targets an internal SVG. Add an accessible name to the button and select the button by that name.
The icon exists but is hidden The assertion checks presence while the requirement is visibility, or CSS keeps it hidden until a state change. Use be.visible for a visual requirement and trigger the user action that should reveal it before asserting.

Reliability and maintenance checklist

  • Start from the element that gives the test its meaning: a labeled control, row, card, or field.
  • Use .find() for descendants and .closest() followed by .find() for elements that share a container.
  • Scope repeated content before selecting the icon.
  • Prefer stable test attributes or accessible names over styling classes and positional selectors.
  • Keep the query and assertion in one Cypress chain so built-in retry behavior can work.
  • Assert the user-relevant property, not merely the existence of an arbitrary SVG.
  • Give every interactive icon control an accessible name and test that control directly.
  • Use an explicit count assertion when uniqueness matters.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is to capture a page image for documentation, a visual check, or an AI workflow rather than interact with the DOM, ScreenshotNeo provides a one-request screenshot API. It accepts consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response reports the page verdict and billing status in X-Page-Verdict and X-Billed headers.

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

For a direct request, see the ScreenshotNeo API documentation:

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

The same call in Python:

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)

And in Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo also offers an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. Options include full-page and lazy-image capture, CSS-selector element capture, dark mode, device presets or custom viewports, retina scale, PDF page controls, custom CSS and JavaScript, clicks before capture, waits, request blocking, headers and cookies, user-agent and authorization settings, timezone and geolocation, transparent backgrounds, resizing, configurable caching, signed links, asynchronous jobs, bulk capture for up to 100 URLs per call, and a usage API. Every feature is available on every plan. The Free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 screenshots, with yearly billing giving two months free.

Best Value
Sale
Logitech K270 Full Size Wireless Keyboard for Windows - Black
  • All-day Comfort: This USB keyboard creates a comfortable and familiar typing experience thanks to the deep-profile keys and standard full-size layout with all F-keys, number pad and arrow keys
  • Built to Last: The spill-proof (2) design and durable print characters keep you on track for years to come despite any on-the-job mishaps; it’s a reliable partner for your desk at home, or at work
  • Long-lasting Battery Life: A 24-month battery life (4) means you can go for 2 years without the hassle of changing batteries of your wireless full-size keyboard
  • Simply plug the USB receiver into a USB port on your desktop, laptop or netbook computer and start using the keyboard right away without any software installation
  • Simply Wireless: Forget about drop-outs and delays thanks to a strong, reliable wireless connection with up to 33 ft range (5); K270 is compatible with Windows 7, 8, 10 or later

Create a free ScreenshotNeo account to use the 1,000 monthly screenshots without a card.

Frequently Asked Questions

Can one Cypress chain select an icon several levels below its anchor?

Yes. .find() searches all descendants, so the icon does not need to be an immediate child.

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.

Should I assert an SVG’s exact shape in every test?

No. Assert the control’s behavior or the icon state your requirement depends on; reserve detailed SVG assertions for rendering-specific tests.

What is the quickest way to diagnose an unexpectedly broad match?

Temporarily add should('have.length', 1) at the scoped point, then tighten the anchor or icon selector until the count reflects the intended element.

Quick Recap

Bestseller No. 1
SaleBestseller No. 3
Logitech K120 Full Size Wired Keyboard USB Plug-and-Play Windows - Black
Logitech K120 Full Size Wired Keyboard USB Plug-and-Play Windows - Black
Plastic parts in K120 include 51% certified post-consumer recycled plastic*; Product carbon footprint: 4.02 kg CO2e
$12.34
SaleBestseller No. 5
Logitech K270 Full Size Wireless Keyboard for Windows - Black
Logitech K270 Full Size Wireless Keyboard for Windows - Black
Plastic parts in K270 include 38% certified post-consumer recycled plastic; Eight hot keys: For instant access to the Internet, e-mail, music volume and more
$23.99

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.