Search code examples
csscss-selectorscypressui-automation

How can select 1 element from the 8 elements matching my selectors. [Cypress test]


I am trying to verify the heading of a section when running a test, using this locater [data-cy="offerBreakUpTableHeaderCellRenderer"] .flex span:first-child I am getting 4 elements I want to select the first one**(Joined)** of the 4 elements

enter image description here


Solution

  • You can do something like this. eq(0) will get the first [data-cy="offerBreakUpTableHeaderCellRenderer"] and then within will make sure that the Joined element only within the [data-cy="offerBreakUpTableHeaderCellRenderer"] is selected.

    cy.get('[data-cy="offerBreakUpTableHeaderCellRenderer"]')
      .eq(0)
      .within(() => {
        cy.contains('span', 'Joined').click()
    
        //Checking number as a string
        cy.contains('span', 'Joined').next().should('have.text', '1')
    
        //checking number as a number
        cy.contains('span', 'Joined')
          .next()
          .invoke('text')
          .then((num) => +num)
          .should('eq', 0 + 1)
      })
    

    If you want to check them independently, you can do this:

    cy.get('[data-cy="offerBreakUpTableHeaderCellRenderer"]')
      .eq(0)
      .within(() => {
        cy.contains('span', 'Joined').click()
    
        //Checking number as a string
        cy.get('span[class*="flex"] span').eq(1).should('have.text', '1')
    
        //checking number as a number
        cy.get('span[class*="flex"] span')
          .eq(1)
          .invoke('text')
          .then((num) => +num)
          .should('eq', 0 + 1)
      })