Search code examples
htmlcypresstestcase

Cypress testcase: Select only text of an element (not the text of its children/descendants)


HTML Code:

<p class="target">
    <span>I am Span 1 of target_value 1*</span>
    <span>I am Span 2 of target_value 2*</span>
    target_value   /* I want to get this value in cypress test case */
</p>

Note*: Both the texts "I am Span 1 of target_value 1" and "I am Span 2 of target_value 2" are dynamic and can change at times.But these spans might contain the text "target_value". In cypress test case how can I select the text "target_value" in

directly(not in its children) and check if it is rendering or not. I just want to get the main text value which is not inside any of its children element.


Solution

  • What you target is a text node. There are 3, but the first two are just spacing chars between spans.

    cy.get('p')
      .then($el => $el[0].childNodes)  
      .then(children => [...children].filter(child => {
        return child.nodeType === 3   // ignore <span>s
          && child.textContent.trim() !== ''  // remove spacing between <span>s
      }))
      .then(textNodes => textNodes[0].textContent.trim())  
      .should('eq', 'target_value   /* I want to get this value in cypress test case */')
    

    If the target text is always last within <p>

    cy.get('p')
      .then($p => $p[0].lastChild.nodeValue.trim())   
      .should('eq', 'target_value   /* I want to get this value in cypress test case */')
    

    Excluding children with .not(children())

    cy.get('p')
      .then($p => $p.contents().not(Cypress.$('p').children()).text().trim())
      .should('eq', 'target_value   /* I want to get this value in cypress test case */')
    

    Clone and remove children

    cy.get('p')
      .then($p => $p.clone().children().remove().end().text().trim())
      .should('eq', 'target_value   /* I want to get this value in cypress test case */')