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)
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.
- String
- Number
- Regular Expression
Example #1: Using contains with string content
cy.contains("Forms").click();
Example #2: Using contains with number content
cy.contains(2019);
Example #3: Using contains with get()
cy.get("span.menu-title").contains("Form Layouts").click();
Example # 4: Use contains with selector and content
cy.contains("span.menu-title","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");
cy.contains("Extra");
cy.contains("Ext");
Example #6: Use contain for
If your element contain html entities non breaking space you just need to use space
// HTML Code
<span>Hello world</span>
// 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
<html>
<body>
<ul>
<li>Java</li>
<li>Python</li>
<li>JavaScript</li>
</ul>
</body>
</html>
Technically the <html>
, <body>
, <ul>
, and last <li>
in the example below all contain "JavaScript".