how to get value attribute of radio input with cypress?

224 views Asked by At

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"

2

There are 2 answers

0
Alapan Das On BEST ANSWER

You can try this:

cy.getAllByRole('radio')
  .first()
  .invoke('val')
  .then((val) => {
    cy.log(val) //logs male
  })
0
Aladin Spaz On

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.