'Best selector for obtaining text using Cypress
I'm learning best practice for Cypress selector strategies. Given that I want to get the release number from the Cypress Releases page, with the following HTML snippet:
<div class="main-content-article-wrapper">
<article class="main-content-article hide-scroll">
<h1 class="main-content-title">Changelog</h1>
<div class="nuxt-content">
<h2 id="9-5-4">
<a href="#9-5-4" aria-hidden="true" tabindex="-1"><span class="icon icon-link">
</span>
</a>9.5.4
</h2>
...what would be the optimal, future proofed selector to use to get the 9.5.4 version number text from frome the <h2>?
My thinking is that the Changelog text for the <h1> is unlikely to change, but the <h2> that contains the text is not a child nor a sibling.
So something like this?
cy.get("div.nuxt-content")
.first("h2").then((txt=>{
const versionTxt = txt.find("a").text()
expect(versionTxt).to.equal('9.5.4')
However, this fails to find the targeted text
Solution 1:[1]
Your test fails because the text '9.5.4' is outside the </a> closing tag and .text() only gives you innerText.
Based on the HTML,
cy.get("div.nuxt-content")
.first("h2").then((txt=>{
const versionTxt = txt.text()
expect(versionTxt).to.equal('9.5.4')
or
cy.get('h2[id="9-5-4"]')
.invoke('text')
.should('eq', '9.5.4')
Solution 2:[2]
You can use the include.text to check the version number.
cy.get('h2#9-5-4').should('include.text', '9.5.4')
Solution 3:[3]
Depending on your use case, using cy.contains could be a viable option. It wouldn't use selectors, but may be a better solution in some cases (such as overly complex HTML that only has one element with a specific text).
// Just getting the element
cy.contains('9.5.4');
// Validating element exists -- implied by above, but explicit below
cy.contains('9.5.4').should('exist');
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Fody |
| Solution 2 | Alapan Das |
| Solution 3 | agoff |
