Nitish Singh
Nitish Singh

Reputation: 215

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.

Upvotes: 5

Views: 2179

Answers (2)

user16695029
user16695029

Reputation: 4430

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

Upvotes: 1

Alapan Das
Alapan Das

Reputation: 18650

You can do something like this. You extract everything and split the string and get the last value and assert or perform any actions.

cy.get('p.target').invoke('text').then((text) => {
  expect(text.split('\n')[3].trim()).to.equal('some value')
})

Upvotes: 1

Related Questions