Contents

    Guides

    How to Use Cypress Get Text for UI Validation

    Published on

    March 2, 2026
    How to Use Cypress Get Text for UI Validation

    Modern applications render content dynamically, update UI components without full page reloads, and rely heavily on JavaScript-driven state changes. In such scenarios, simply clicking elements is not enough.

    Tests must validate what is actually displayed, verify that attributes carry correct values, confirm dropdown data integrity, and ensure user inputs are captured accurately. Without reliable data extraction strategies, assertions become fragile and tests lose diagnostic value.

    This guide explains how to install and configure Cypress, locate elements effectively, and extract text, attributes, dropdown data, and input values for reliable UI validation.

    Install and Configure Cypress Environment

    Before extracting text, attributes, or dropdown values, the test environment must be correctly configured. A stable setup ensures consistent execution, proper dependency resolution, and reliable browser control.

    Start by installing Node.js, since Cypress runs within a Node-based ecosystem. Then initialize a project and install Cypress as a development dependency. Once installed, launching Cypress for the first time generates the required folder structure, including the cypress directory, configuration files, and sample test files.

    Configuration plays a critical role in data extraction reliability. Key setup considerations include:

    • Base URL configuration: Defining a base URL in the Cypress configuration file simplifies navigation commands and avoids repetitive hardcoding.
    • Test file structure: Organizing test files by feature or module improves maintainability as extraction logic grows.
    • Environment variables: Storing API endpoints or test-specific data in environment settings keeps tests clean and reusable.
    • Browser selection: Running tests across multiple browsers helps validate that DOM structures behave consistently.

    A properly configured environment reduces flakiness and ensures that element selection and data extraction behave predictably across test runs.

    Find and Select Elements in Cypress Tests

    Accurate data extraction depends on selecting the correct elements consistently. If selectors are unstable or overly dependent on layout structure, tests will fail even when the application functions correctly. The goal is to target elements in a way that reflects user interaction while remaining resilient to UI changes.

    Cypress primarily interacts with the DOM using CSS selectors. Elements can be located using IDs, classes, attributes, tag names, or custom data attributes. Among these, custom attributes such as data-* are generally the most stable because they are less likely to change during UI redesigns.

    Common selection strategies include:

    • ID-based selection: Suitable when IDs are unique and stable.
    • Class-based selection: Useful for grouped elements but can become fragile if styling changes.
    • Attribute selectors: Effective for targeting elements with specific properties such as type, name, or role.
    • Data attribute selectors: Recommended for test reliability, especially in dynamic applications.
    • Hierarchical selection: Locating elements within a specific container to reduce ambiguity.

    Choosing the right selector strategy directly impacts the stability of text and attribute extraction. Strong selectors reduce ambiguity, prevent accidental matches, and make assertions more predictable across application updates.

    Extract Text from Elements in Cypress

    Validating visible content is one of the most common test requirements. Whether confirming success messages, table data, headings, or button labels, extracting text ensures the UI reflects the expected application state.

    Text extraction typically targets the rendered content of DOM elements. However, modern frameworks may update content asynchronously, so tests must account for timing and state changes. Cypress automatically retries commands until assertions pass or time out, which helps stabilize text validation in dynamic environments.

    Key considerations when extracting text include:

    • Visible vs hidden text: Ensure the assertion targets rendered text that users can actually see.
    • Whitespace handling: Trim unnecessary spaces when validating formatted content.
    • Dynamic updates: Validate text after triggering actions that modify UI state.
    • Multiple elements: When extracting from lists or tables, handle collections carefully to avoid partial matches.
    • Conditional rendering: Confirm that elements exist before extracting text in cases where visibility depends on user interaction.

    Structured text extraction improves assertion clarity and strengthens confidence that the UI communicates accurate information under real usage scenarios.

    Get Attributes from HTML Elements in Cypress

    In many scenarios, validation goes beyond visible text. Applications often rely on HTML attributes to control behavior, accessibility, navigation, and state. Extracting attribute values allows tests to verify whether elements are configured correctly under different conditions.

    Attributes such as href, src, value, disabled, checked, aria-*, and data-* frequently carry business-critical information. Validating these ensures that links point to the correct destinations, form controls reflect accurate states, and accessibility properties are properly applied.

    Important considerations when extracting attributes include:

    • State validation: Confirm whether elements are enabled, disabled, checked, or selected based on application logic.
    • Dynamic attribute updates: Some attributes change after user interaction, so extraction must occur after the relevant action.
    • Accessibility verification: Validating aria-* attributes helps ensure compliance with accessibility standards.
    • Data-driven attributes: Custom data-* attributes may contain identifiers or configuration values essential for functional validation.
    • Link and resource verification: Checking href and src attributes ensures proper navigation and asset loading.

    Attribute extraction strengthens test coverage by validating both UI presentation and underlying element configuration, ensuring the interface behaves correctly at a structural level.

    Text extraction may appear straightforward when executed locally, but real-world environments introduce subtle variations that can impact assertions. Different browser engines such as Blink in Chrome, WebKit in Safari, and Gecko in Firefox handle whitespace normalization, font rendering, pseudo-elements, and DOM updates slightly differently.

    Platforms like BrowserStack provide access to real desktop and mobile browsers across operating systems, allowing Cypress tests to run in production-like environments. This strengthens confidence that text extraction, attribute validation, dropdown verification, and input value assertions remain stable across the environments users actually rely on.

    Extract Dropdown Options List in Cypress

    Dropdowns often represent controlled datasets such as categories, user roles, countries, or status values. Validating the available options ensures that backend responses, configuration rules, and UI rendering remain aligned.

    Instead of validating only the selected value, robust tests verify the entire options list. This helps detect missing entries, incorrect ordering, duplicate values, or unintended changes introduced during feature updates.

    When extracting dropdown options, consider the following:

    • Static vs dynamic dropdowns: Some lists are hardcoded, while others are populated via API responses and may require synchronization with network activity.
    • Order validation: In workflows where sorting matters, confirm that options appear in the expected sequence.
    • Value-text mapping: Ensure the displayed label matches the underlying option value used in form submission.
    • Conditional visibility: Some options may appear based on user roles or prior selections.
    • Multi-select scenarios: Extract and validate all available options before asserting selected combinations.

    Find Elements Using Selector Playground

    Efficient element identification reduces test development time and improves selector accuracy. Cypress provides a built-in Selector Playground within its Test Runner to help inspect elements and generate reliable selectors directly from the application UI.

    Selector Playground analyzes the DOM and suggests a unique selector for the chosen element. This is especially useful when working with complex component hierarchies or dynamically generated classes.

    When using Selector Playground, keep these points in mind:

    • Selector quality review: Generated selectors should be reviewed to avoid overly specific paths that may break after UI updates.
    • Preference for data attributes: If available, prioritize data-* attributes over auto-generated class names.
    • Avoid deep DOM chaining: Extremely long CSS paths increase fragility.
    • Uniqueness validation: Ensure the selector matches only the intended element.
    • Maintain readability: Clean selectors improve long-term test maintainability.

    Extract Values from Text Inputs and Textareas

    Form inputs often capture user-provided data that drives application workflows. Validating these values ensures that typing actions, auto-filled data, default states, and post-submission behaviors function as expected.

    Unlike standard elements where text is extracted from visible content, input fields store data within the value attribute. Therefore, extraction logic must target the underlying field value rather than rendered text.

    When working with text inputs and textareas, consider the following:

    • Default value validation: Confirm pre-filled or placeholder-driven defaults before user interaction.
    • Post-typing verification: Ensure the field reflects exactly what was entered, including special characters.
    • Clearing and re-entry: Validate behavior when inputs are cleared and updated.
    • Disabled or read-only states: Confirm that restricted fields prevent modification.
    • Form state persistence: Verify whether values remain intact after page reloads or navigation events.

    Accurate input value extraction ensures that form-driven features operate correctly and that user data is handled consistently across workflows.

    Conclusion

    Reliable UI validation in Cypress depends on more than triggering actions. Accurate extraction of text, attributes, dropdown options, and input values ensures that tests validate real user-visible behavior and underlying element configuration.

    To strengthen this validation further, running Cypress tests on real browsers and devices through platforms like BrowserStack helps ensure that text rendering, input handling, and DOM behavior remain consistent across operating systems and browser versions, reducing environment-specific failures in production.

    Try BrowserStack for Free

    Data-rich bug reports loved by everyone

    Get visual proof, steps to reproduce and technical logs with one click

    Make bug reporting 50% faster and 100% less painful

    Rating LogosStars
    4.6
    |
    Category leader

    Liked the article? Spread the word

    Continue reading

    No items found.

    Put your knowledge to practice

    Try Bird on your next bug - you’ll love it

    “Game changer”

    Julie, Head of QA

    star-ratingstar-ratingstar-ratingstar-ratingstar-rating

    Overall rating: 4.7/5

    Try Bird later, from your desktop