the reluctant tester

Perpetual learner of the craft of Software Testing,Servant Leadership and creating better Teams

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: Logo

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

Facebook photo

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

Connecting to %s

About Me

I’m Sunjeet Khokhar

An experienced People Leader,Practice Lead  and Test Manager .

I am driven by the success of people around me, am a keen student of organisational behaviour and firmly believe that we can be better craftspeople by being better humans first.

CoNNECT with Me

%d bloggers like this: