Rahul Yadav
Rahul Yadav

Reputation: 3197

how to get value attribute of radio input with cypress?

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

Answers (2)

Aladin Spaz
Aladin Spaz

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

Alapan Das
Alapan Das

Reputation: 18650

You can try this:

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

Upvotes: 1

Related Questions