'How to loop through datatable to validate select control option values in Cypress?

Below is a step & datatable in my Cypress / Cucumber test:

And Results per page drop down has the below options
      | 10  |
      | 50  |
      | 80  |
      | 100 |
      | 150 |

In my test, I want to loop through the options inside a select control, & validate the option values match the above values.

Below is my step defintion code.

And('Results per page drop down has the below options', (dataTable) => {
  dataTable.rawTable.forEach(($ele) => {
    cy.log($ele.toString());
  });
  
  cy.get('[id=mat-select-2-panel]').find('.mat-option').each(($el, index, $list) => {
    cy.log($el.text());
  });
});

I've been able to loop through the datatable & loop through the option's, but I want to know how can I merge the above code so that I can compare each option value against the datatable.

Can someone please tell me how I can do this, & what changes to my code are required.



Solution 1:[1]

With forEach loop you can also get the index values and then you can use the eq command to get the particular element and then apply a text assertion, Something like this:

And('Results per page drop down has the below options', (dataTable) => {
  dataTable.rawTable.forEach(($ele, index) => {
    cy.get('[id=mat-select-2-panel]')
      .find('.mat-option')
      .eq(index)
      .should('have.text', $ele.toString())
  })
})

Solution 2:[2]

The approach depends on if dataTable has the exact same order as the elements, if so

And('Results per page drop down has the below options', (dataTable) => {
  cy.get('[id=mat-select-2-panel]').find('.mat-option').each(($el, index, $list) => {

    // When expected values match exactly the sequence of elements
    expect($el.text()).to.eq(dataTable[index])

  });
})

If the order can be different,

And('Results per page drop down has the below options', (dataTable) => {
  cy.get('[id=mat-select-2-panel]').find('.mat-option').each(($el, index, $list) => {

    // When you want to verify the element against the list, but order may not correspond
    expect(dataTable.includes($el.text())

  });
})

You can add other checks as necessary,

  • for handling additional spaces = $el.text().trim()
  • for handling numeric values in dataTable = $+el.text()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alapan Das
Solution 2 Fody