Cypress Radio Button Assertion

Viewed 2281

I am new to Cypress and JavaScript and want to know how to assert that a radio button is selected.

I have cy.get('[type="radio"]').should('be.checked') but that seems to validate all of the radio buttons on the screen.

I want to assert that a specific radio button is selected.

1 Answers

Which commands you use depends on the HTML you are working with,

At minimum, you can expect the radios to be labelled for the user.

Labels on the left, use .next()

html: `
    <label>One</label>
    <input type="radio" checked>

    <label>Two</label>
    <input type="radio" >
`,
test: `

cy.contains('label', 'One')
  .next()                                // select the next element
  .should('have.attr', 'type', 'radio')  // confirm it's type radio (optional)
  .should('be.checked')

`

Labels on the right, use .prev()

html: `
    <input type="radio" checked>
    <label>One</label>

    <input type="radio" >
    <label>Two</label>
`,
test: `

cy.contains('label', 'One')
  .prev()                                // select the previous element
  .should('have.attr', 'type', 'radio')  // confirm it's type radio (optional)
  .should('be.checked')

`

Labels have "for" attribute, use .get('input#my-id')

html: `
    <input type="radio" id="one" checked>     
    <label for="one">One</label>

    <input type="radio" id="two" >
    <label for="two">Two</label>
`,
test: `

cy.get('input#one')                      // select by id used to associate the label
  .should('be.checked')

`

Labels are grouped by "name", use .get('input[value="my-value"]')

html: `
    <input type="radio" name="my-radios" value="one" checked>
    <label for="one">One</label>

    <input type="radio" name="my-radios" value="two" >
    <label for="two">Two</label>
`,
test: `

cy.get('input[value="one"]')           // select by group value attribute
  .should('be.checked')

`
Related