An Overview of the Popular .contains() Command in Cypress

No votes yet.
Please wait...

.contains() is probably the most popular Cypress command, especially if you work as a developer or software tester.

Though its name sounds like a statement, it’s actually a typical command of test selection.

Of course, you can disagree by saying that all selection commands create elements but this article is actually about something different.

We will explain why this command is so useful and why you should take it into account, by analyzing a simple example.
Cypress Tool

Cypress Tool

Let’s start from the structure. It’s quite simple and easy to memorize.

<h1>Car and another transports</h1>
<ul>
<li>Car ????</li>
<li>Bicycle????</li>
<ul>

The easiest way to use it is to select an element that contains a certain text block.

If a user is familiar with this command, he/she definitely knows how to select an element, by using the following text:

cy
.contains(‘Car’)

It’s very easy and convenient. The title will be selected in the result.

And you won’t need to enter the whole text — you’ll simply need to add the Cars word.

By the way, if we had used the Car word as text, the result would have been completely different. Car would have appeared for the second time.

By default, .contains() can search for the whole expressions and always return the first element with the required description.

Narrowing search results

Now we suggest narrowing the search of parent/child/dual commands to analyzying the latter.

cy
.contains(‘Car’) // the title will be slected
cy
.get(‘li’)
.contains(‘Car’) // the “Car ????” will be selected

This command helps to find a required element, therefore, if your test contains the <button> button, whose text is located inside the <span> element, the <button> will be selected.

You can read more about prioritization in Cypress here.

But there is another option — transmitting two arguments inside the .contains() function. In this case, a primary element is a selector itself, that can define the search area of our element:

cy
.contains(‘ul’, ‘Pear’)

The correspondence to the text

If it doesn’t matter whether you use lower-case letters or upper-case letters, you can add an additional parameter to a function — it gives a command to ignore an alphabetical register:

cy
.contains(‘cars’, { matchCase: false })

It’s very helpful when user tests are located in a separate variable or inside a file.

You can also use various mutations of a selected language. If this doesn’t help, you can use regex to find any line:

cy
.contains(/Car/)

That’s it. This command sounds like a variable and can be used in this way but the main task of this function is to select an appropriate element.

The .contains() command is a useful and efficient substitution of xPath and complex Selenium CSS selectors.

Leave A Comment