Open In App

Cypress - Text Verification

Last Updated : 22 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.
text_verify
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".
testt_1
Output

2. 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".
testt_2
Output

3. 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.
testt_3
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".
testt_4
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.
testt_5
Output

3. 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".
testt_6
Output

4. 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.
testt_7
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

  1. 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.
  2. 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.
  3. 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

  1. 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.
  2. 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.


Next Article

Similar Reads