Open In App

Cypress - contains() Method

Last Updated : 05 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Cypress is a popular testing framework for web applications. It provides a lot of useful methods to interact with web elements, one of which is the contains() method. In this article, we will explore the contains() method in Cypress, its usage, and examples.

Usages

The contains() method checks if an element contains a specific text or value. It can be used in various ways, such as:

  • Checking if an element contains a particular text
  • Checking if an element contains a particular value
  • Checking if an element contains a particular attribute

Syntax:

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

Arguments:

  • selector: A string representing the element to search for.
  • content: A string or a regular expression representing the content to search for.
  • options: An object with additional options.

Examples

Example 1: Checking if an element contains a specific text

Let's say we have an HTML element like this:

HTML
<!DOCTYPE html>
<html>
<head>
  <title>Example 1</title>
</head>
<body>
  <div id="myDiv">Hello World!</div>
</body>
</html>

We can use the contains() method to check if the element contains the text "Hello World!":

JavaScript
// cypress/integration/example1.spec.js
describe('Example 1', () => {
  it('should contain the text "Hello World!"', () => {
    cy.visit('example1.html');
    cy.get('#myDiv').contains('Hello World!');
  });
});

Output:

Capture
Output

In this example, cy.get('#myDiv') is used to get the element with the id "myDiv", and then contains('Hello World!') is used to check if the element contains the text "Hello World!".

Example 2: Checking if an element contains a specific value

Let's say we have an HTML element like this:

HTML
<!DOCTYPE html>
<html>
<head>
  <title>Example 2</title>
</head>
<body>
  <label id="myLabel">
    <input id="myInput" value="Hello World!" />
    Hello World!
  </label>
</body>
</html>

We can use the contains() method to check if the element contains the value "Hello World!":

JavaScript
// cypress/integration/example2.spec.js
describe('Example 2', () => {
  it('should contain the value "Hello World!"', () => {
    cy.visit('example2.html');
    cy.get('#myLabel').contains('Hello World!');
  });
});

Output:

Capture


In this example, cy.get('#myInput') is used to get the element with the id "myInput", and then contains('Hello World!') is used to check if the element contains the value "Hello World!".

Conclusion

In this article, we have explored the contains() method in Cypress, its usage, and examples. The contains() method is a powerful tool for checking if an element contains a specific text, value, or attribute. By using this method, you can write more robust and reliable tests for your web applications.


Next Article

Similar Reads