typescriptcypresscypress-each

Cypress+TS, how to get second text that wrapped double quotes?


I got this web page to test claim number. But I am not able to extract the same.

<h1 class="jss41 undefined" style="text-transform: capitalize; display: flex; align-items: center; margin-bottom: 0.5rem;">
"Claims #"
"75078"
</h1>

The xpath I am trying to get is

export const getClaimsHeader = () => cy.xpath("//h1[contains(@class,'undefined')]")

This is the code I am trying to get the claim Number

  getClaimsHeader()
  .each((header) => {
    claimNum = header.text().split('#');
    actualClaimNumber = claimNum[1];
    
  })
  .then(() => {
    expect(claimNumber).to.equal(actualClaimNumber);
  });

But actualClaimNumber is displayed as blank because header.text() is returning only "Claims #"


Solution

  • You may have textNodes inside the <h1> although it's not apparent from the HTML.

    If so, here is a function to try out which should return all the textNodes in an array:

    function getTextNodes($el) {
      const childNodes = $el[0].childNodes
      const textNodes = [...childNodes].filter(child => child.nodeType === Node.TEXT_NODE)
      const texts = textNodes.map(textNode => textNode.nodeValue.trim())
      return texts
    }
    

    Use it like this

    getClaimsHeader().each((header) => {
      const texts = getTextNodes(header);
      console.log(texts)              // check which part of the array is the number
      const claim = texts[1]          // for example
    })
    

    Since you're using .each() I presume there are multiple headers?

    If so, your .then() does not receive each claim number, only the last one.