0
0
Cypresstesting~3 mins

Why cy.contains() for text matching in Cypress? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a single command can save you hours of frustrating searching in your tests!

The Scenario

Imagine you have a webpage with many buttons and links, all with different texts. You want to check if a button with the text "Submit" is present. Manually searching through the HTML code or clicking every button to find it is like looking for a needle in a haystack.

The Problem

Manually scanning the page or writing long selectors for each element is slow and tiring. You might miss the exact text or pick the wrong element. This causes mistakes and wastes time, especially when the page changes often.

The Solution

The cy.contains() command in Cypress lets you quickly find any element by its visible text. It works like a smart search that finds the right element without complicated selectors. This makes tests faster, clearer, and less error-prone.

Before vs After
Before
cy.get('button').eq(3).click(); // guessing the button position
After
cy.contains('button', 'Submit').click(); // directly finds button by text
What It Enables

With cy.contains(), you can write simple, reliable tests that focus on what users see and interact with, not on complex code details.

Real Life Example

Testing a signup form where the "Register" button might move or change style, but the text stays the same. Using cy.contains('button', 'Register') ensures your test clicks the right button every time.

Key Takeaways

Manually finding elements by text is slow and error-prone.

cy.contains() finds elements by visible text easily.

This makes tests simpler, faster, and more reliable.