Wai Yan Hein
Wai Yan Hein

Reputation: 14841

Cypress: getting the attribute value of the element in the each

I am building a web application using JavasScript. I am writing tests for the Front-End using Cypress. In my test, I am trying to loop through the elements using each, https://docs.cypress.io/api/commands/each#Promises and trying to get the attribute value of the element in the loop.

This is my code

cy.get('.list-items').each($item => {
    $item.invoke('attr', 'data-status').should('contain', 'Pending')
})

As you can see in my test, I am trying to get the data-status attribute of the element. But when I run the test, it is giving me the following error.

$item.invoke is not a function

How can I get the attribute value of the element of each() function?

Upvotes: 0

Views: 805

Answers (2)

You can also use the $item attribute directly. If you need to click on the corresponding item.

    cy.get('.list-items').each($item => {
      if($item.attr('data-status') === 'Pending'){
        cy.wrap($item).click()
      }
    })

Upvotes: 0

Alapan Das
Alapan Das

Reputation: 18576

You have to use cy.wrap() for $item

cy.get('.list-items').each($item => {
    cy.wrap($item).invoke('attr', 'data-status').should('include', 'Pending')
})

Upvotes: 1

Related Questions