Cypress - Text Verification
Last Updated :
22 Aug, 2024
There are many reasons why text verification is necessary to guarantee that web applications show the right information to the users. The process of asserting the title of a page, the contents of a modal, or the text in a button is the same and simple in Cypress.
In Cypress, text verification typically involves using the .should() assertion, which allows you to check the content of an element. Cypress also provides more enhanced search features that involve partial text search and regex search in case the text is not rigid or sometimes precise.
Setting Up Cypress for Text Verification
Before diving into text verification, ensure that Cypress is correctly installed and set up in your project. If you haven't set up Cypress yet, follow these steps:
Install Cypress:
npm install cypress --save-dev
Open Cypress:
npx cypress open
Create a Test File:
In the cypress/e2e folder, create a new test file, e.g., text_verification.cy.js.
With Cypress set up, you're ready to start writing text verification tests.
Basic Text Verification Techniques
1. Verifying Exact Text
To verify that an element contains specific text, you can use the cy.contains() or cy.get() commands combined with .should('have.text', text). This method ensures that the element's text matches the specified text exactly.
Syntax:
cy.contains('Submit').should('have.text', 'Submit');
or
cy.get('.button-class').should('have.text', 'Submit');
Example:
Create a simple HTML file with a button containing the text "Submit":
<button class="button-class">Submit</button>
Write the Cypress test to verify the exact text:
JavaScript
describe('Exact Text Verification', () => {
it('should verify that the button contains the text "Submit"', () => {
cy.visit('cypress/file.html');
cy.get('.button-class').should('have.text', 'Submit');
});
});
Running the Test:
- Open Cypress Test Runner using npx cypress open.
Cypress Test Runner- Select the text_verification.cy.js file.
- Observe the test running and check that the output verifies the button's text as "Submit".
Output2. Verifying Partial Text
Sometimes, you only need to verify that an element contains part of the text rather than the exact text. Cypress’s cy.contains() is useful for these scenarios, as it checks if any element contains the specified text.
Syntax:
cy.contains('Sub');
Example:
Create an HTML file with a paragraph containing the text "Subscribe to our newsletter":
<p>Subscribe to our newsletter</p>
Write the Cypress test to verify partial text:
JavaScript
describe('Partial Text Verification', () => {
it('should verify that the paragraph contains the partial text "Sub"', () => {
cy.visit('cypress/file.html');
cy.contains('Sub');
});
});
Running the Test:
- Open Cypress Test Runner.
- Run the text_verification.cy.js file.
- Observe that Cypress successfully verifies the presence of the partial text "Sub".
Output3. Case-Insensitive Text Verification
Cypress performs text verification case-sensitively by default. To verify text without worrying about case sensitivity, you can use regular expressions with the i flag for case insensitivity.
Syntax:
cy.contains(/submit/i);
Example:
Use an HTML file with a button labeled "SUBMIT":
<button>SUBMIT</button>
Write the Cypress test to verify the text case-insensitively:
JavaScript
describe('Case-Insensitive Text Verification', () => {
it('should verify the button text case-insensitively', () => {
cy.visit('cypress/file.html');
cy.contains(/submit/i);
});
});
Running the Test:
- Run the test through the Cypress Test Runner.
- Verify that the test passes, confirming the button's text regardless of the case.
Output
Advanced Text Verification Techniques
Advanced text verification is needed when working with more complex scenarios, such as using regular expressions, verifying text within specific elements, or checking text across multiple elements.
1. Using Regular Expressions
Regular expressions allow you to perform more flexible text verification. For example, you can check for multiple potential text values within a single element.
Syntax:
cy.contains(/^Submit|Cancel$/);
Example:
Use an HTML file with a button that could have "Submit" or "Cancel" as its text:
<button>Cancel</button>
Write the Cypress test to verify the text using a regular expression:
JavaScript
describe('Regular Expression Text Verification', () => {
it('should verify the button text is either "Submit" or "Cancel"', () => {
cy.visit('cypress/file.html');
cy.contains(/^Submit|Cancel$/);
});
});
Running the Test:
- Run the test using the Cypress Test Runner.
- Verify that the test passes by confirming that the button text matches either "Submit" or "Cancel".
Output
2. Verifying Text Within Elements
In some cases, you might want to verify that a specific element contains certain text, rather than checking the whole page. Use the cy.get() command followed by .should('contain.text', text).
Syntax:
cy.get('.submit-button').should('contain.text', 'Submit');
Example:
Create an HTML file with a button inside a form:
<form>
<button class="submit-button">Submit</button>
</form>
Write the Cypress test to verify text within the button element:
JavaScript
describe('Text Verification Within Elements', () => {
it('should verify the button within the form contains the text "Submit"', () => {
cy.visit('cypress/file.html');
cy.get('.submit-button').should('contain.text', 'Submit');
});
});
Running the Test:
- Run the test in Cypress.
- Observe that the test passes by correctly verifying the text within the button element.
Output3. Verifying Text Across Multiple Elements
When you need to verify that multiple elements on a page contain certain text, you can loop through the elements using cy.get().each() and perform assertions on each element.
Syntax:
JavaScript
cy.get('.list-item').each(($el) => {
cy.wrap($el).should('contain.text', 'Item');
});
Example:
Create an HTML file with a list of items:
HTML
<ul>
<li class="list-item">Item 1</li>
<li class="list-item">Item 2</li>
<li class="list-item">Item 3</li>
</ul>
Write the Cypress test to verify text across all list items:
JavaScript
describe('Text Verification Across Multiple Elements', () => {
it('should verify each list item contains the text "Item"', () => {
cy.visit('cypress/file.html');
cy.get('.list-item').each(($el) => {
cy.wrap($el).should('contain.text', 'Item');
});
});
});
Running the Test:
- Run the test in Cypress.
- Verify that the test passes, confirming that each list item contains the text "Item".
Output4. Verifying Text with Dynamic Data
Dynamic data refers to text that can change based on user input or data fetched from an API. To handle this, you can store the expected text in a variable and then verify it.
Syntax:
JavaScript
const dynamicText = 'Hello, World!';
cy.get('.greeting').should('have.text', dynamicText);
Example:
Create an HTML file with a dynamic greeting:
<div class="greeting">Hello, World!</div>
Write the Cypress test to verify dynamic text:
JavaScript
describe('Verifying Dynamic Text', () => {
it('should verify the dynamic greeting text', () => {
const dynamicText = 'Hello, World!';
cy.visit('path/to/your/file.html');
cy.get('.greeting').should('have.text', dynamicText);
});
});
Running the Test:
- Run the test in Cypress.
- Confirm that the test correctly verifies the dynamic greeting text.
Output
Here's what you might see in the Cypress Test Runner when verifying text:
- Passing Tests: A green checkmark next to the test name indicates that all assertions passed.
- Failing Tests: If a test fails, you'll see a red cross, and the command that caused the failure will be highlighted. You can click on the failed command to see more details, including the expected and actual values.
Best Practices for Text Verification in Cypress
- Use Specific Selectors: To minimize or eliminate the false positives one has to use specific selectors such as IDs or classes to select the elements to verify.
- Avoid Hard-Coding Text: Ideally, use of a text should not be put hard coded in the test where possible. It’s better to use variables or constants where it is easier to maintain the code.
- Handle Dynamic Content Carefully: Make sure that your tests for the verification of dynamic content are immune to timing problems by incorporating the right wait strategies.
Troubleshooting Common Issues
- Text Not Found: If Cypress does not locate the text make sure that the element is visible and not hidden or obscured by another element.
- Timing Issues: Some of the commands used in SAP are as follows: cy. wait() or cy. get(). should(‘be. visible’) for dealing with the timing problems in case the text is not quickly loaded.
Conclusion
Text verification is actually an important part of Cypress testing as it involves checking the text content on your webpages against defined threshold. Summing up, the author shares the examples of efficiency of the collected techniques and best practices, allowing for getting powerful and stable text verification tests in Cypress.
On the Cypress side, the execution of these tests and the viewing of the output of these tests is simple, which is helped by the fact that you can see the various tests running in real-time and you can immediately see if there are any problems. This capability increases the chances of your robotic testing as being accurate and dependable.
Similar Reads
Cypress - visit() Method
The visit() method in Cypress is used to navigate the browser to a specific URL in your test. It allows you to open web pages, whether they are local or remote, for testing purposes. This is one of the most fundamental commands in Cypress as it sets up the starting point for most test cases by loadi
3 min read
Next.js Cypress Testing
Cypress is an open-source website testing tool that is used to automate tests for JavaScript web applications. It is designed for end-to-end testing and it can be used for Unit tests and Integration tests as well. It is fast, reliable, and can run in real-time directly in the browser.It's built to w
3 min read
Cypress - get() Method
The get() method in Cypress is used to select elements from the DOM using a CSS selector. Once selected, you can chain various Cypress commands to interact with or assert properties on these elements. It's a core command that you'll use frequently in your Cypress tests.Usageget() is versatile and ca
3 min read
Cypress - within() Method
The within() method in Cypress is used to scope the search for DOM elements within a specific element. It is helpful when you want to limit the scope of your Cypress commands (such as get(), find(), contains(), etc.) to a particular section of the DOM. This is especially useful when dealing with nes
3 min read
Cypress - origin() Method
Cypress is an open-source website testing tool that tests for JavaScript web applications. It is designed for end-to-end testing and it can be used for unit tests and integration tests as well. It is fast, reliable, and can run in real-time directly in the browser.It's built to work with any front-e
4 min read
Cypress - session() Method
Managing sessions in web applications is crucial for handling user authentication, tracking user interactions, and maintaining state across different pages. In Cypress, the session() method is a powerful tool for managing and persisting session data across different tests. This feature allows you to
4 min read
Cypress - eq() Method
The eq() method in Cypress is a powerful utility that allows you to select a specific element from a group of elements based on its index. This method is particularly useful when you need to interact with or make assertions on a specific element within a collection of elements that share the same se
3 min read
Cypress - viewport() Method
The viewport() method in Cypress allows you to programmatically set the browser's viewport size for your tests. This is especially useful when testing responsive designs, ensuring that your web application behaves correctly on different screen sizes, from mobile to desktop. By simulating various dev
2 min read
Cypress - filter() Method
Cypress is a popular JavaScript testing framework used for web automation testing. It provides a lot of useful methods to interact with web elements, one of which is the filter() method. In this article, we will discuss the filter() method in Cypress, its usage, syntax, arguments, and examples.Usage
2 min read
Cypress - writeFile() Method
The writeFile() method in Cypress allows you to write data to a file on your local file system during a test. This can be useful for storing logs, test data, or configurations that need to be saved during the test run. It can write JSON, text, or any other type of file supported by Node.js.Usages of
3 min read