Discover how a single command can save you hours of frustrating searching in your tests!
Why cy.contains() for text matching in Cypress? - Purpose & Use Cases
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.
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 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.
cy.get('button').eq(3).click(); // guessing the button position
cy.contains('button', 'Submit').click(); // directly finds button by text
With cy.contains(), you can write simple, reliable tests that focus on what users see and interact with, not on complex code details.
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.
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.