grubyfat
grubyfat

Reputation: 55

How to .log() an element that contains element that contains a text in Cypress

Basically I have 4 rows

4 rows
Rows

and I want to .log() only one of them which contains a label that has a text 'Car1.2'

code
code

html
html

row code
row code

Upvotes: 0

Views: 4101

Answers (3)

You can move to the parent row by specifying .parents('.row')

See parents() command

Please note that .parents() travels multiple levels up the DOM tree as opposed to the .parent () command which travels a single level up the DOM tree.

Like this

it('finds labels', {includeShadowDom:true}, () => {

  cy.contains('#chunker #label', 'Car1.2')
    .parents('.row')
    .then($row => {
      cy.log($row.text())
    })
})

Upvotes: 0

Nopal Sad
Nopal Sad

Reputation: 644

There's another way to use .contains(), you can specify the row class as the first parameter and it will return the row having the label text "Carl1.2" somewhere inside it.

Combining two selectors used here get('#chunker').find('.row') allows you to do this

cy.contains('#chunker .row', 'Carl1.2`)   // simple to obtain the row
  .then($row => {
    cy.log($row)
  })    

Add includeShadowDom:true option to find the the label

cy.contains('#chunker .row', 'Carl1.2`, {includeShadowDom:true})   
  .then($row => {
    cy.log($row)
  })    

Upvotes: 1

Alapan Das
Alapan Das

Reputation: 18634

Do you mean something like this, if you want to just print the text Car1.2

cy.contains('#label', 'Car1.2').then(($ele) => {
  cy.log($ele.text())
})

If you to print the whole row where Car1.2 is printed, you first have to reach the parent element of the row and then using within scope the next commands within that specific row only and then print the row texts, something like this:

cy.contains('#label', 'Car1.2')
  .parent()
  .parent()
  .parent()
  .parent()
  .within(() => {
    cy.get('#label').each(($ele) => {
      cy.log($ele.text())
    })
  })

To make sure all your commands automatically traverse shadow dom's, go to cypress.json(if cypress version < 10) or cypress.config.js(if cypress version >= 10) and write:

includeShadowDom: true

Upvotes: 1

Related Questions