How to Assert Text in Cypress: Simple Syntax and Examples
In Cypress, you can assert text by using
cy.get(selector).should('have.text', 'expected text') or cy.contains('expected text'). These commands check if the element contains exactly or partially the specified text, helping verify UI content easily.Syntax
Use cy.get(selector).should('have.text', 'expected text') to assert exact text content of an element. Alternatively, cy.contains('text') finds an element containing the text anywhere inside it.
Parts explained:
cy.get(selector): Selects the element by CSS selector..should('have.text', 'expected text'): Asserts the element's text exactly matches.cy.contains('text'): Finds element containing the text partially or fully.
javascript
cy.get('selector').should('have.text', 'expected text') cy.contains('expected text')
Example
This example shows how to check if a heading has the exact text and how to find a button containing specific text.
javascript
describe('Text Assertion Example', () => { it('checks exact text and partial text', () => { cy.visit('https://example.cypress.io') cy.get('h1').should('have.text', 'Kitchen Sink') cy.contains('type').click() cy.url().should('include', '/commands/actions') }) })
Output
Test passes if the <h1> text is exactly 'Kitchen Sink' and the button containing 'type' is clicked successfully.
Common Pitfalls
Common mistakes include:
- Using
have.textwhen the element has extra whitespace or child elements, causing assertion failure. - Confusing
have.text(exact match) withcontain.text(partial match). - Not waiting for the element to appear before asserting text.
Use should('contain.text', 'partial text') for partial matches and trim text if needed.
javascript
/* Wrong: exact match fails due to extra spaces or child elements */ cy.get('selector').should('have.text', 'ExactText') /* Right: partial match works better in such cases */ cy.get('selector').should('contain.text', 'ExactText')
Quick Reference
| Command | Purpose | Example |
|---|---|---|
| cy.get(selector).should('have.text', text) | Assert exact text content | cy.get('h1').should('have.text', 'Hello') |
| cy.get(selector).should('contain.text', text) | Assert partial text content | cy.get('p').should('contain.text', 'Welcome') |
| cy.contains(text) | Find element containing text | cy.contains('Submit').click() |
Key Takeaways
Use cy.get(selector).should('have.text', text) for exact text assertions.
Use cy.get(selector).should('contain.text', text) for partial text matches.
cy.contains(text) helps find elements by visible text easily.
Watch out for extra spaces or child elements that can cause exact text assertions to fail.
Always ensure the element is visible before asserting text.