cypresscypress-conditional-testing

Cypress - How to only click button if it contains "chevron_right"


This button has 2 states, "chevron_right" when disabled. And "expand_more" when enabled.

Its default state is "chevron_right"

The following code will click on the button the first time. But once it is enabled will error saying because it cannot find "chevron_right". Does anyone know what i am doing wrong?

cy.get('#TreeView mat-nested-tree-node').find('button').first().then(button => {
    if (cy.wrap(button).contains('chevron_right')) {
        cy.wrap(button).click()
                
    } else{
        cy.log("Do nothing")
    }
})

There are multiple buttons on the page that will have these 2 states, so i am unable to just search for 1 instance of it.


Solution

  • Don't cy.wrap(button) use jQuery instead.

    The text() method from jQuery gets the innerText and .includes() is the javascript method to check for "contains".

    cy.get('#TreeView mat-nested-tree-node').find('button').first()
      .then($button => {
        if ($button.text().includes('chevron_right')) {
            cy.wrap($button).click()
                    
        } else{
            cy.log("Do nothing")
        }
    })
    

    The $ prefix on yielded parameter button is convention, but it's not needed to make this work.