In cypress testing how to check if these tiles are in order?

Viewed 29

There are multiple chapters on a page in a format as shown in the image. I have to add a test in cypress which checks if chapter numbers are in order. In case they get shuffled (as shown in image), the test should show an error.

Also the text "Chapter 1" can be selected so cypress can read it on the screen. These tiles have other information as well but I only want the chapter number tested.

enter image description here

2 Answers

One way to check is by extracting all the numbers from each tile and checking if the original array is the same as the sorted array.

cy.get(".tile-selector")
  .then(($el) => {
    // use lodash .map() to get innerText of each element
    // then extract number and convert to int
    const originalOrder = Cypress._.map($el, (n) => {
      return +n.innerText.split(" ")[1];
    });
    // make a copy of the original array to sort
    const sortedOrder = [...originalOrder];
    // use comparator to sort numbers
    sortedOrder.sort((a, b) => a - b);
    expect(originalOrder, "Chapters are in order").to.deep.equal(sortedOrder);
  });

Here is an example.

The simplest way is to just compare the combined texts

const expectedText = 'Chapter 1Chapter 3Chapter 5Chapter 13';

cy.get(selector)                                         // all the chapter cards
  .invoke('text')                                        // get combined text
  .should('eq', expectedText)

If you find there is white-space and linefeeds (\n) making the combined comparison difficult, map and trim the individual texts

const expectedOrder = ['Chapter 1', 'Chapter 3', 'Chapter 5', 'Chapter 13'];

cy.get(selector)
  .then($els => $els.toArray().map(el => el.innerText.trim())   // trim whitespace
  .should('deep.eq', expectedOrder)                             // deep.eq for array

Use the deep.equal assertion to test the order is correct.

Related