Home > database >  Best selector for obtaining text using Cypress
Best selector for obtaining text using Cypress

Time:04-26

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 >
  <article >
    <h1 >Changelog</h1>
    <div >
      <h2 id="9-5-4">
        <a href="#9-5-4" aria-hidden="true" tabindex="-1"><span >
             </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

CodePudding user response:

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')

CodePudding user response:

You can use the include.text to check the version number.

cy.get('h2#9-5-4').should('include.text', '9.5.4')

CodePudding user response:

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');
  • Related