0
0
CypressHow-ToBeginner ยท 3 min read

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.text when the element has extra whitespace or child elements, causing assertion failure.
  • Confusing have.text (exact match) with contain.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

CommandPurposeExample
cy.get(selector).should('have.text', text)Assert exact text contentcy.get('h1').should('have.text', 'Hello')
cy.get(selector).should('contain.text', text)Assert partial text contentcy.get('p').should('contain.text', 'Welcome')
cy.contains(text)Find element containing textcy.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.