Checking radio buttons in Cypress

Stacey :

I'm very new to Javascript and it's my only second week using Cypress, so I need help in getting radio buttons to be clicked. I'm getting errors from Cypress all the time.

The element that I'm trying to check looks like: <input class="XyzTypeRadio" type="radio" name="zzz_type" value="2">

And what I tried to implement after reading the Cypress documentation (at https://docs.cypress.io/api/commands/check.html#Syntax )was: cy.get('[type="radio"]').first('.XyzTypeRadio').check('value=2') Also tried simply .... .check('2') and ... .check('Xyz')

sina :

Try this:

cy.get('[type="radio"].XyzTypeRadio').check("2")

Or if you don't care which radio button is checked, you could check the first one:

cy.get('[type="radio"].XyzTypeRadio').first().check()

Takeaways:

  • The first() function does not understand selectors, that's why we need to pass our selector ".XyzTypeRadio" to get().
  • The check() function expects the value or values as its argument, so instead of "value=2" we simply give it "2".
  • The check() function does a bit of selecting, ie the result of everything before calling check("2") is a list of inputs and the check("2") function searches and selects the one whose value is "2".
  • We could use first().check() if we want to check the first radio button, or we could remove first() and check a radio button with a specific value using check("2").

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=174389&siteId=1