Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cypress get button within subject

I have a case where I need to test buttons that are generated through activity on the site (making a game creates a button on their homepage). These buttons should take the user to their game portal.

The buttons are contained within .sidebar--button subject, they are listed from top to bottom.

First I attempted to click the nth button in .sidebar--button by using:

    it('selects the 3rd game in the sidebar', () => {
    cy.get('.sidebar--button').eq(2).click()
    cy.wait(1000)
    cy.url()
        .should('include', 'portal')

This failed as I cannot use .eq to click an element.

Then I tried to use .within to select a single generated button within the .sidebar--button using:

it('deletes the current game', () => {
    cy.get('.sidebar--button').should('have.length', 1)
    cy.get('.sidebar--button').within((".sidebar--button") => {
        cy.get('.button').click()
    })
    cy.wait(1000)
    cy.url()
        .should('include', 'portal')

This failed as well.

How can I cy.get('nth button').click() with only the buttons contained within .sidebar--button ?

like image 647
J.Long Avatar asked Dec 22 '25 09:12

J.Long


2 Answers

Does this button has different text? if yes, then use

cy.get('.sidebar--button').contains('whatever the text is').click()
like image 190
Gary Avatar answered Dec 23 '25 22:12

Gary


You can use for that css selectors. For example if you have scenario like this .parent>.child*4>button you can access to third element by .parent:nth-child(3) button. for more exact css selector i have to know the html structure.

----- Edited -----

Working selector for this case .sidebar--button:nth-child(3) .button.

like image 24
Przemyslaw Jan Beigert Avatar answered Dec 23 '25 23:12

Przemyslaw Jan Beigert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!