乐闻世界logo
搜索文章和话题

How to extract text content from a div using Cypress?

1个答案

1

When performing automated testing with Cypress, extracting text content from a div is a fundamental and common operation. Below are the steps and examples to achieve this:

Step 1: Locate the target div

First, determine the selector for this div. Assuming the div has a specific ID or class, use these attributes to identify it.

Step 2: Use the .text() method to retrieve text content

Cypress provides the .text() method to capture the text content of an element. This method retrieves the text value of the element, including all its child elements' text.

Example Code

Assume the following HTML structure:

html
<div id="message">欢迎来到我们的网站!</div>

We can write the following Cypress test code to extract the text from this div:

javascript
describe('Text extraction Test', () => { it('gets text from a div', () => { // Navigate to the page cy.visit('http://example.com'); // Locate the div and extract text cy.get('#message').then(($div) => { // $div is the jQuery element const text = $div.text(); // Log the text to verify the result cy.log('Extracted text: ' + text); }); }); });

Considerations

  • Ensure the element is present in the DOM before invoking .text(). Use cy.get() combined with .should('be.visible') assertions to verify the element's existence and visibility.
  • The text returned by .text() includes all child elements' text content. If you need the text of a specific child element, target it more precisely.

By following these steps and methods, you can easily extract text content from any div, which is highly valuable for verifying the displayed content of page elements.

2024年6月29日 12:07 回复

你的答案