DEV Community

Cover image for How to check multiple checkboxes at once with Cypress
Walmyr
Walmyr

Posted on • Updated on

How to check multiple checkboxes at once with Cypress

Learn how to remove code duplication from your Cypress tests by calling the .check() command only once when you want to check all the checkboxes in a section of the application ☑️

I don't know about you, but I don't really like code duplication. So today, I'm going to show you a technique to eliminate some duplication when dealing with checkboxes using the Cypress test automation framework.

To exemplify, I will use a sample application created using only static files (HTML, CSS, and a background image).

Note: the app text is in Portuguese

In this application, as shown below, there is a section with the label Select the technologies you use:

checkboxes-screenshot

Since all checkboxes are contained in a div with id check, I can check them all with a single command like this:



// cypress/integration/checkboxes.spec.js

describe('Checkboxes', () => {
  beforeEach(() => {
    cy.visit('https://bit.ly/3vswFBe')
  })

  it('checks all checkboxes with one command', () => {
    cy.get('#check input[type="checkbox"]')
      .as('checkboxes')
      .check()

    cy.get('@checkboxes')
      .each(checkbox => {
        expect(checkbox[0].checked).to.equal(true)
      })
  })
})


Enter fullscreen mode Exit fullscreen mode

And since the .check() command chained to cy.get() checks more than one checkbox, all checkboxes are checked if the used selector is not specific to a single element, which is the case.

With that, I can have a new cy.get(), this time passing as argument the alias created earlier ('@checkboxes'), to check that they are all really checked.

Easy ha?

For more details on the .check() functionality, I recommend reading the Cypress official docs.


Did you like this “Pinch of Cypress”?

Leave a comment.


Are you curious and want to learn more about testing automation with Cypress? I was hoping you could get to know my Cypress courses on Udemy.


This post was originally published in Portuguese on the Talking About Testing blog.


👋 Until next time and happy testing!

Top comments (2)

Collapse
 
prasannakumar1 profile image
Prasanna-Kumar-1

Thats a nice one. Thanks @walmyrlimaesilv

Collapse
 
walmyrlimaesilv profile image
Walmyr

I'm glad you liked it.