Cypress .get() vs .contains()

Cypress .get() vs .contains()

Cypress is a Javascript-based FE testing tool that is very popular today. I have been using it for end-to-end tests recently at work. In Cypress, one accesses elements on the DOM and verifies that they are behaving properly (sounds like I am talking about a 4-year old kid). To get these elements, one often uses the cy.get() method or the cy.contains() method. Let's look at the differences.

get()

While both methods return DOM elements, the main difference between the two is the arguments - the HOW behind getting DOM elements. The get() method takes an element selector as its arguments in the form of a string. This can be a class, id or even the element type. Let's look at an example:

<div className="container">
   <ul className="sports">
      <li>Soccer</li>
      <li>Basketball</li>
      <li>Rock Climbing</li>
   </ul>
</div>
cy.get('.sports')  // returns the element with selector === 'sports'
// in this case, the <ul> element

So passing a string to the get() method will return the element with the matching selectors applied to it.

contains()

Now the contains() method is very similar, but instead of looking for elements with matching selectors, it searches for elements with matching text (and by 'text' I mean what is passed to the DOM). Again, let's look at the same example:

<div className="container">
   <ul className="sports">
      <li>Soccer</li>
      <li>Basketball</li>
      <li>Rock Climbing</li>
   </ul>
</div>
cy.contains('Soccer') // returns the element with text === 'Soccer'
// in this case, the <li> element

It is important to remember that this text is case-sensitive, and it needs to be an exact match of the element's text (some styles make text look all caps, but is not so).

Distinction between the two

Let's change our example code a little by adding another element to the top of our list called 'sports' (notice that this text matches our <ul> className).

<div className="container">
   <ul className="sports">
      <li>sports</li>
      <li>Soccer</li>
      <li>Basketball</li>
      <li>Rock Climbing</li>
   </ul>
</div>

What would happen when calling cy.get('sports')? What about cy.contains('sports')? Would there even be a difference? Let's see.

cy.get('sports') // yields the <ul> element where selector === 'sports'
// still returns the same element as the first example

cy.contains('sports') // yields the <li> element where text === 'sports'
// does not return the <ul> with matching selector, still looks for text

As you might have guessed, the contains() method did not care about the selectors and still found the element with the correct text. Hopefully you have a better understanding of when to use get() and when to use contains().