Cypress - Working with div tables - Validating text on each row

Viewed 70

I want to check if the first column of each row's text starts with "AA", "BB" or "CC". But I couldn't manage it on div table. I can only select and check the first row (code below). But I also tried with selecting the whole column and tried with using cy.each & cy.wrap and got errors too.

How can I check the first column for each row's text? (Table has 40-45 rows.)

The table looks like this:

enter image description here

enter image description here

Right now I can only check the first row with the code below. How can I check all the rows like this? Is the code below clear to you by the way?

cy.get('div[row-index="0"]')
           .eq(1)
           .invoke('text')
           .then(text => {
            const productID = text.trim();
             let correctProductIDPrefix = false;
             ['AA', 'BB', 'CC'].forEach(possibleProductIDPrefix => {
             if (!correctProductIDPrefix) {
               correctProductIDPrefix = productID.startsWith(possibleProductIDPrefix);
             }
         });
         expect(correctProductIDPrefix).to.be.true;
       });

Thanks in advance!

2 Answers

To perform the same test on all rows

  • select all the rows (change [row-index="0"] to [row-index])
  • use .each() to run test on all rows
  • sub-select just the column you want, in case some other column also has the prefix and gives you a false-positive result
  • use Array.some() method to check at least one prefix matches
const possibleProductPrefixes = ['AA', 'BB', 'CC']     // define once outside test

cy.get('div[row-index]')           // selects every row
  .each($row => {

    const $col = $row.find('[col-id="orderNumber"]')  // pick out the column
    const productId = $col.text().trim()

    const correctProductIDPrefix = possibleProductPrefixes.some(prefix => {
      return productId.startsWith(prefix)
    })

    expect(correctProductIDPrefix).to.be.true;
  });

Ref Array.prototype.some()

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array.

You can do something like this:

let prefix = ['AA', 'BB', 'CC']
cy.get('.ag-cell-value').each(($ele, index) => {
  expect($ele.text().trim().startsWith(prefix[index])).to.be.true
})
Related