javascriptcypresscustom-data-attribute

How to check the order of elements based on data attributes in Cypress


Let say I have a parent div with the id of "container" and it has four children with specific data attribute named data-test. How do I check if each child is in the right order? Let's say the right order should be the following:

  1. "black-leather"

  2. "emerald-stone"

  3. "diamond-blade"

  4. "fire-sword"

    <div id="container">
      <div data-test="diamond-blade">...</div>
      <div data-test="fire-sword">...</div>
      <div data-test="emerald-stone">...</div>
      <div data-test="black-leather">...</div>
    </div>
    

In my test I have something like

it('Should have the specific order....', () => {
  cy.get('#container').should('exist')
    .contains('not sure what to put here')
})

Solution

  • Attribute selectors require square brackets, and they don't "have.text" instead you must invoke the .attr() method to get the attribute value.

    cy.get('#container [data-test]').eq(0)
      .invoke('attr', 'data-test').should('eq', 'diamond-blade')
    
    cy.get('#container [data-test]').eq(1)
      .invoke('attr', 'data-test').should('eq', 'fire-sword')
    
    cy.get('#container [data-test]').eq(2)
      .invoke('attr', 'data-test').should('eq', 'emerald-stone')
    
    cy.get('#container [data-test]').eq(3)
      .invoke('attr', 'data-test').should('eq', 'black-leather')