简体   繁体   中英

Checking radio buttons in Cypress

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')

(edited and working answer)

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").
cy.get('[value="Other"]').first().check()

这对我有用,因为有 3 个单选按钮,每个按钮都有一个值,所以只需选择正确的值

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM