DEV Community

Cover image for cy.get() vs. cy.contains()
Walmyr
Walmyr

Posted on • Edited on

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

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.

Top comments (2)

Collapse
 
shalinibaskaran12 profile image
Shalini Baskaran

Thank you it helped a lot to understand difference between cy.get() and cy.contain(). While I was learning about Cypress assertion library I came across interesting article on "Complete guide to cy.should() command". It also explain about how to use cy.should() with cy.get() and cy.contain().

Collapse
 
walmyrlimaesilv profile image
Walmyr

Cool, thanks for sharing.