1

I have this code

        cy.visit('http://localhost:3000/')
        cy.get('.list').each((list, index, lists) => {
            cy.contains('Learn').click()
            cy.url().should('include', '/localhost')

            cy.get(`[data-testid="card-input-${index}"]`)
                .type('Learn Cypress')
                .should('have.value', 'Learn Cypress')
            cy.get(`[data-testid="btnAdd-${index}"]`).click()


            cy.get(".card").each((card, index, cards) => {
                cy.get(cards).should('have.length', 4)
            })

        })

I need this line to return only cards from the specific list. Right now it returns all cards from all lists.

 cy.get(cards).should('have.length', 4)

I tried playing with literals, but it return [object object]

 cy.get(`${cards}>card`).should('have.length', 4)
Robert Veselý
  • 219
  • 3
  • 11

2 Answers2

1

So the first each, is looping over the list and I am assuming that within the list you want to access the cards, So you can do something like this:

cy.visit('http://localhost:3000/')
cy.get('.list').each((list, index, lists) => {
  cy.contains('Learn').click()
  cy.url().should('include', '/localhost')

  cy.get(`[data-testid="card-input-${index}"]`)
    .type('Learn Cypress')
    .should('have.value', 'Learn Cypress')
  cy.get(`[data-testid="btnAdd-${index}"]`).click()

  cy.wrap(list).within(() => {
    cy.get('.card').should('have.length', 4)
    //or
    cy.get('.card').its('length').should('eq', 4)
    //or
    cy.get('.card')
      .its('length')
      .then((len) => {
        cy.get('.card').should('have.length', len)
      })
  })
})
Alapan Das
  • 17,144
  • 3
  • 29
  • 52
  • This seems great! What if I want to write something like cy.get('.card').should('have.length', ('.card').length) ? have.length doesnt seem to return the same value as .length – Robert Veselý Jul 03 '22 at 16:04
  • You can also invoke length by using `its('length')`, maybe you can try this. Updated the answer. – Alapan Das Jul 03 '22 at 16:13
1

The reason you have been getting all the cards from all list is due to the cy.get() searching from the root DOM element. In order to limit your search to a previous DOM element you'll want to use either .within() or .find().

cy.visit('http://localhost:3000/')
cy.get('.list').each((list, index) => {

  cy.contains('Learn').click()
  cy.url().should('include', '/localhost')
  cy.get(`[data-testid="card-input-${index}"]`)
    .type('Learn Cypress')
    .should('have.value', 'Learn Cypress')
  cy.get(`[data-testid="btnAdd-${index}"]`).click()

  cy.wrap(list)
    .find('.card')
    .should('have.length', 4)
})
jjhelguero
  • 2,281
  • 5
  • 13