cy.get() vs. cy.contains()

Walmyr - Aug 8 '22 - - Dev Community

Get to know one of the differences between the commands cy.get and cy.contains

Here's a simple but helpful piece of information to better use Cypress and understand when to use one command or another.

Do you know the difference between the two lines of code below?

cy.get('tr:contains(User 1)')
Enter fullscreen mode Exit fullscreen mode
cy.contains('tr', 'User 1')
Enter fullscreen mode Exit fullscreen mode

They look quite similar, don't they?

However, they are actually different.

While cy.get gets one or more DOM elements.

cy.contains gets only one DOM element.

Here's an example where we need to combine cy.get with jQuery's contains selector instead of using cy.contains.

Just to reinforce.

cy.get('tr:contains(User 1)') // get ALL table rows which contain User 1 in their content
Enter fullscreen mode Exit fullscreen mode
cy.contains('tr', 'User 1') // get the first table row which contains User 1 in its content
Enter fullscreen mode Exit fullscreen mode

I hope you find this helpful information.


Did you like the content? Leave a comment.


Curious and want to learn more about Cypress Testing Automation?

Check out my online courses on Udemy.


👋 Until next time, and happy testing!


This content was translated to Portuguese and can be found on the Talking About Testing blog.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player