0
0
Cypresstesting~5 mins

cy.contains() for text matching in Cypress

Choose your learning style9 modes available
Introduction

We use cy.contains() to find elements on a webpage by looking for specific text. It helps us check if the text we expect is visible.

You want to click a button or link by its text label.
You need to check if a message or heading appears on the page.
You want to find an element without knowing its exact HTML structure.
You want to verify that certain text is present after an action.
You want to select an element that contains dynamic text.
Syntax
Cypress
cy.contains(text)
cy.contains(selector, text)
cy.contains(text, options)

text is the string you want to find on the page.

You can optionally provide a selector to narrow down where to look.

Examples
Finds the first element containing the text 'Submit' anywhere on the page.
Cypress
cy.contains('Submit')
Finds a <button> element that contains the text 'Submit'.
Cypress
cy.contains('button', 'Submit')
Checks if the text 'Welcome, user!' appears anywhere on the page.
Cypress
cy.contains('Welcome, user!')
Sample Program

This test visits a page, finds a button or link with the text 'type', clicks it, and then checks if the URL changed as expected.

Cypress
describe('Test cy.contains()', () => {
  it('finds and clicks a button by text', () => {
    cy.visit('https://example.cypress.io')
    cy.contains('type').click()
    cy.url().should('include', '/commands/actions')
  })
})
OutputSuccess
Important Notes

cy.contains() is case sensitive by default.

You can use regular expressions for partial or case-insensitive matching, e.g., cy.contains(/submit/i).

It automatically waits for the element to appear before failing the test.

Summary

cy.contains() helps find elements by their visible text.

You can use it with or without a selector to narrow the search.

It is useful for clicking buttons, links, or verifying text presence.