Exploring the Cypress API – getting and asserting on a DOM element’s children

A common operation during Web UI tests is to view and validate contents of a drop down.

As part of my exploration of the ever likable Cypress automation toolset, I recently wrote a UI workflow tests that amongst other things validated the contents and count of a drop down list’s elements.

I was dreading that I would have to figure out a way using JavaScript/JQuery to select the drop down and iterate my way through the drop down’s children and perform an assertion on the item and count  the children.

But, behold.., the fact fact that the Cypress API has handy dandy method to get all the children of a DOM element

Using .children() and the readable Chai assertions made this a joy

it('verify the total count and existence of a particular element in the dropdown',() => {
// get the element and it's associated children
cy.get('#sort-by-menu-header > div > ul').children()
// perform the assertion on existence of a particular item in the drop down
.should('contain','New Arrivals')
// perform the assertion on the number of children i.e. options in the drop down

Bonus tip-

Note the clever use of “and” in adding multiple assertions on the element , avoiding the use of multiple “shoulds” and making the code human readable.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s