How can I find and click button element in cypress by the text on the button

Viewed 1429

I am having trouble finding a way of locating this element with cypress. I dont want to use the class name due to its complexity, and would like to use "Support" to keep my code clean.

<button type="button" class="border-secondary shadow-none btn btn-outline-primary">Support</button>

I have attempted cy.get('button').contains('Support').click() without success.

2 Answers

There's another variation of .contains() that will give you just the "Support" button

cy.contains('button', 'Support')

The only problem with using cy.contains, is that what if you want to verify the css color or text on it? cy.contains doesn't work most of the time. I personally would still use the class but add a wildcard "*" ex: cy.get('button[class*="btn-outline-primary"]') <-- next what you want to do is check it on the webpage, so go to the webpage you are testing and: rightClick/Inspect, then use ctl f, then copy and paste: button[class*="btn-outline-primary"] in the find section <-- this way you'll know that you can find it and Cypress does see it. If it does work then:

cy.get('button[class*="btn-outline-primary"]').should(verifyText =>
{
     expect(verifyText).have.text('Support').have.css('background-color', 'rgb(0, 0, 0)')

})

Try using cy.contains() when you just want to only minor stuff like clicking. But if you need to assert, try defining it more with cy.get(). Hope it helps.

Related