Cypress: Finding the content of a specific td element

Viewed 291

I need to find the content of a specific td element based on the content of the next td element in the row.

The markup (simplified):

<table id="oversiktOverSoknaderTable">
 <tr data-e2e-selector="soknad-linje">
  <td data-e2e-selector="status">Trukket</td>
   <td data-e2e-selector="soknadProsjektNavn">Endret søknad</td>
   <td>Lån</td>
   <td data-e2e-selector="soknadId" id="2"></td>
 </tr>
 <tr data-e2e-selector="soknad-linje">
  <td> ...

There can be multiple rows, all with the same selector (data-e2e-selector="soknad-linje">. The issue at hand is to verify that the correct status is showing for the correct name. (Sorry for not translating the selector names, but I think they're quite self-explanatory.)

What I want to do, is to use .should('contain'.'value') to verify that the text in the data-e2e-selector="status" quals "Trukket" for the line where the data-e2e-selector="soknadProsjektNavn" is "Endret søknad". (As it is in the above example.)

Ideas?

5 Answers

Assuming Endret søknad is a unique value in your table.

Since you have data-e2e-selector in your elements you can use the follow

cy.get('#oversiktOverSoknaderTable') // hopefully this is unique enough
  .should('be.visible') // assertion to avoid element detached from DOM

cy.contains('[data-e2e-selector="soknad-linje"]', 'Endret søknad') // gets row with unique string
  .should('be.visible')
  .find('[data-e2e-selector="status"]') // searches in row for element
  .should('have.text', 'Trukket') // has status text

Something like this, you can do

cy.contains('td', 'Endret søknad')
  .sibling('[data-e2e-selector="status"]')
  .should('contain', 'Trukket')

where sibling() takes a selector to specify which one.

There is also .prev() command.

Like @jjhelguero I would also recommend being specific with data-e2e-selector in the selector.

cy.contains('td[data-e2e-selector="soknadProsjektNavn"]', 'Endret søknad') 
  .prev('td[data-e2e-selector="status"]') 
  .should('have.text', 'Trukket') 

You can do something like this:

cy.contains('td', 'Endret søknad')
  .parent('tr')
  .within(() => {
    cy.get('[data-e2e-selector="status"]').should('have.text', 'Trukket')
  })

If you're getting detached from DOM error, try keeping the commands preceding .should() (which triggers retry) as short as possible.

cy.contains('[data-e2e-selector="soknad-linje"]', 'Endret søknad') // row with project
  .should('contain', 'Trukket')                                    // confirm the status

or

cy.get('[data-e2e-selector="soknad-linje"]')
  .should('contain', 'Endret søknad') 
  .should('contain', 'Trukket') 
Related