When working on automation with Cypress, we often need to fetch text from a webpage element.
Cypress provides several ways to do this:
- Using
.invoke('text')after selecting an element withcy.get() - Using jQuery methods inside a
.then()callback - Using
.should()for text assertions without manually extracting text
Below are clean and correct examples demonstrating each approach.
✅ 1. Fetch Text Using invoke('text')
cy.get(‘css-selector’)
.invoke(‘text’)
.then((text) => {
cy.log(‘Fetched Text:’, text);
});
✅ 2. Fetch Text Using jQuery (.then() callback)
cy.get(‘css-selector’)
.then(($el) => {
const text = $el.text();
cy.log(‘Text from jQuery:’, text);
});
✅ 3. Fetch Text Using .should()
cy.get(‘css-selector’)
.should(‘have.text’, ‘Expected Text’);
If you need partial match:
cy.get(‘css-selector’)
.should(‘contain.text’, ‘Partial Text’);
✅ 4. Using Aliases to Re-use the Element Text
cy.get(‘css-selector’)
.invoke(‘text’)
.as(‘elementText’);
cy.get(‘@elementText’).then((text) => {
cy.log(‘Text from alias:’, text);
});
✅ 5. Fetching Text from Multiple Elements
cy.get(‘.items li’)
.then(($items) => {
const texts = […$items].map(el => el.innerText.trim());
cy.log(‘List of texts:’, JSON.stringify(texts));
});
✔ Summary
| Method | Best For | Example |
|---|---|---|
invoke('text') | Text extraction | .invoke('text') |
jQuery (then) | Advanced manipulation | $el.text() |
should() | Assertion | .should('contain.text', ...) |
| Aliases | Re-use extracted text | .as('name') |
| Loops | Multiple elements | Map through $elements |