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

Walmyr @walmyrlimaesilv

About: I'm a software engineer who loves testing. I'm also a clean coder, blogger, YouTuber, Cypress.io Ambassador, online instructor, speaker, an active member of tech communities.

Location:
Barcelona, Spain
Joined:
Nov 19, 2019

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

Publish Date: Aug 8 '22
16 2

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.

Comments 2 total

  • Shalini Baskaran
    Shalini BaskaranJul 17, 2023

    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().

    • Walmyr
      WalmyrJul 18, 2023

      Cool, thanks for sharing.

Add comment