简体   繁体   中英

How to verify table's column data is sorted by name or not

I have one project where I want to do some sorting. When the user click on the column name data should be show in sorted by name.

Is it possible to do in Cypress using POM?

You can extract the column data from the page, then sort it. Afterwards, click on app sort by name and match.

Here is a working simplified example .

cy.get('.selector-to-get-column-data')
  .then(($el) => {
    // use lodash .map() to get innerText of each element
    // then sort the array
    return Cypress._.map($el, "innerText").sort();
  })
  .as("sortedArray")

// action to sort column

cy.get("@sortedArray").then((sortedArray) => {
  cy.get(".selector-to-get-column-data")
    .then(($el) => {
      // use lodash .map() to get innerText of each element
      // then sort the array
      return Cypress._.map($el, "innerText").sort();
    })
    .then(cy.log)
    .should("deep.equal", sortedArray);
})

You can create an array with all the elements in sorted order in lower case. Then after sorting extract each text from the column and match it against the array elements.

cy.get('selector').click() //To trigger the sorting

//Save the sorted texts in a array
const sortedTexts = ['apple', 'ball', 'cat', 'dice']

//Loop over column texts and match it agains the sortedTexts
cy.get('column-selector').each(($ele, index) => {
  expect($ele.text().toLowercase().trim()).to.equal(sortedTexts[index])
})

In case you have a dynamic list, you can create two arrays one before sorting and one after sorting, then compare the two, something like this:

var beforeSort = []
var afterSort = []
cy.get('column-selector').each(($ele) => {
  beforeSort.push($ele.text().trim())
})

cy.get('selector').click() //To trigger the sorting

cy.get('column-selector').each(($ele) => {
  afterSort.push($ele.text().trim())
}).then(() => {
  expect(beforeSort.sort()).to.eq(afterSort)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM