Cypress custom command for element selection

We started using in one of our modern application built in React, and the journey with Cypress is incredible so far.

I’m working on a series of posts on my journey with Cypress and how I’m using it for end-to-end testing.

Last week, I saw this awesome open-source sample repository shared by team. This repo contains a test app and example tests using lots of recommended practices. I liked using The custom command for element selection as one of the recommended practices implemented in this repository

We’re using a data-testid attribute to select elements and perform actions on them:

The above code works great, but making a shorthand command like getBySelLike reads better than using cy.get(). I refactored the tests and implemented a custom command from the example and named as getByDataTestSel to select elements as shown in below code snippet:

This custom command makes tests more readable and offers specific API to select an element which have data-test* attribute. You can find more details in Cypress documentation on how to implement custom commands.

More on soon.

Happy Testing!

One thought on “Cypress custom command for element selection

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 )

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