Darksymphony
Darksymphony

Reputation: 2693

Cypress - verify if each table row in one column contains the same item

I have a table, however some kind of ag-grid, created by DIV's, not real table element:

<div role="row" row-index="1" >
<div col-id="name">Name 1</div>
<div col-id="age">25</div>
</div>

<div role="row" row-index="2" >
<div col-id="name">Name 1</div>
<div col-id="age">25</div>
</div>

I want to verify, if EACH field with col-id="name" contains the same item. I am testing kind of filtering, so if user filters the Name 1, I want to check each row, if there is only Name 1 and nothing else.

As each field which I need to check has the same col-id, I tried it this way:

cy.get('div[col-id="name"]').contains('Name 1')

or

cy.get('div[col-id="name"]').should('contain','Name 1')

but both cases passes even if some field contains another name, because it finds at least one match.

How to assert that each field with col-id="name" should contain ONLY Name 1 ?

Upvotes: 2

Views: 4249

Answers (3)

Fody
Fody

Reputation: 32044

Maybe use .each() to test the elements individually

cy.get('div[col-id="name"]')
  .each($el => {
    expect($el.text()).to.eq('Name 1')
  })

Without .each()

cy.get('div[col-id="name"]')
  .should($els => {
    const names = [...$els].map(el => el.innerText)
    expect(names.every(name => name === 'Name 1').to.eq(true)
  })

Upvotes: 3

Alapan Das
Alapan Das

Reputation: 18626

In case you don't want to apply assertion and just print out statements stating whether the element was found/not found, you can do like this:

cy.get('div[col-id="name"]').each(($ele, index) => {
  if ($ele.text().trim() == 'Name 1') {
    cy.log('Item Found at position ' + index)
  } else {
    cy.log(
      'Expected Item Not found at position ' +
        index +
        '. Instead the item was ' +
        $ele.text().trim()
    )
  }
})

Upvotes: 0

You can verify the combined text of all elements

cy.get('div[col-id="name"]')
  .invoke('text')
  .should('eq', 'Name 1'.repeat(2))  // assuming two elements, equals "Name 1Name1"

or, this is better for asynchronous fetching of name

cy.get('div[col-id="name"]')
  .should('have.text', 'Name 1'.repeat(2))  // equals "Name 1Name1"

When element count is unknown

cy.get('div[col-id="name"]')
  .then($els => {
    const count = $els.length
    cy.wrap($els).should('have.text', 'Name 1'.repeat(count))  
  })

Upvotes: 5

Related Questions