top of page

Cypress: Extracting Text & Attributes Values

In automated testing, it's often not enough to just click buttons — you need to verify that the content on the page is correct. Cypress makes it easy to extract values like:


  • Label and button text

  • Input values

  • Attributes like placeholder, class, or id


In this post, we’ll look at how to read, store, and assert text and attributes using Cypress, all based on the real login form on radeksto.com/test/login.


Why Extract Values?


Extracting values is essential when you want to:

  • Validate static text (like labels or headings)

  • Verify what the user typed in a form input

  • Check placeholder, class, or aria attributes for accessibility or visual feedback

  • Store values temporarily for use in later steps


1. Extract Label Text

Use .invoke('text') to get the visible text inside a label, button, or heading.

Useful when you're checking if form fields are labeled correctly.


2. Save Text Using .as() for Reuse

If you want to extract text once and use it later, store it with .as() and refer to it as an alias.

Great for avoiding repeated DOM queries or asserting values in later test steps.


3. Extract Class or Attribute Values

Want to confirm a class or another attribute is applied correctly? Use .invoke('attr', 'attributeName').

Useful for checking if a specific style or behavior is applied (e.g., error class, active state).


4. Read Placeholder and Input Values

You can also verify an element’s placeholder attribute, or even the actual value typed by the user.

This is perfect when you want to validate form input values without submitting the form.


Full Cypress Test Example

Summary: When to Use What

Cypress Method

Use Case

Example

.invoke('text')

Read visible text

cy.get('label').invoke('text')

.invoke('attr', ...)

Get any attribute (class, id, etc.)

cy.get().invoke('attr', 'class')

.invoke('val')

Get value from form inputs

cy.get('input').invoke('val')

.as() + alias

Save values or subjects

cy.get().invoke('text').as('labelText')


 
 
bottom of page