Contains in Cypress

Profile picture for user devraj

In Cypress, contains is used to get the DOM element containing the text. If DOM contain more than one element with desired text it will match the first one.

There are basically 4 variations of contains exists:

cy.contains(content, options)
cy.contains(selector, content)
cy.contains(selector, content, options)

We will discuss 2 here which are without options and remaining 2 in next article. Here content could be of 3 types, we will discuss first 2 right now, regular expression is completely different topic which we will discuss later.

  1. String
  2. Number
  3. Regular Expression

Example #1Using contains with string content


Example #2: Using contains with number content


Example #3: Using contains with get()

cy.get("").contains("Form Layouts").click();

Example # 4: Use contains with selector and content

cy.contains("","Form Layouts").click();

Example #5: You don't need to specify the complete word or combination. For example, for text "Extra Components" you can only specify "Extra" in contains or just "Ext"

cy.contains("Extra Components");

Example #6: Use contain for  

If your element contain html entities non breaking space   you just need to use space

// HTML Code

// Cypress code
cy.contains('Hello world')

Example #7: Use contain with <pre> tag

Unlike other tags, <pre> doesn't ignore leading, trailing, or duplicate whitespaces as shown below, so in cypress contains you need to specify in a same way:

// Pre code
<pre>                 Hello,           World      !</pre>

# Cypress Code
cy.get('pre').contains('                 Hello,           World      !') 

Example #8: Same text multiple elements


Technically the <html><body><ul>, and last <li> in the example below all contain "JavaScript".