cypresscypress-each

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 ?


Solution

  • 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)
      })