Reputation: 3197
I have a radio element <input type="radio" name="gender" value="male" />
below is my cypress code
cy.getAllByRole("radio").first().click()
how do I get the value attribute of the radio element? something like this
const radioValue = cy.getAllByRole("radio").first().getValue() //"male"
Upvotes: 0
Views: 331
Reputation: 9718
To be unambiguous, the value="male"
is an attribute so you would use
cy.getAllByRole('radio')
.first()
.invoke('attr', 'value')
.should('eq', 'male') // assert it
.then(value => cy.log(value)) // or pass it down the chain
The command .invoke('val')
is getting the property, and only works for the selected radio option, which by default is the first option.
If you tried it on the second option, it would fail.
<input type="radio" name="gender" value="male" />
<input type="radio" name="gender" value="female" />
cy.getAllByRole('radio')
.eq(1) // take the second
.invoke('attr', 'value')
.should('eq', 'female') // ✅ passes!
cy.getAllByRole('radio')
.eq(1)
.invoke('val')
.should('eq', 'female') // ❌ fails!
cy.getAllByRole('radio')
.eq(1)
.click() // change the selected item
cy.getAllByRole('radio')
.eq(1)
.invoke('val')
.should('eq', 'female') // ✅ now it passes
In summary, you can check attributes at any time, but checking the property only works after the click action occurs.
Upvotes: 6
Reputation: 18650
You can try this:
cy.getAllByRole('radio')
.first()
.invoke('val')
.then((val) => {
cy.log(val) //logs male
})
Upvotes: 1