DEV Community

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

Posted on • Edited on

14 1

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.

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more