Cypress: Introduction to Custom Query
With latest version 12, Cypress has given ability to its users to write Custom Queries
If you are new to Cypress, Cypress provides vast variety of queries like cy.get() cy.find() etc..
These queries does auto retry when querying for elements and this is a great feature for dynamic loading elements.
Now looking at Custom queries, one might think that why do we even need them. Let’s consider below HTML Table.
If we observe, the last row “New Company” loads after sometime dynamically.
And we have to write test to get Contact information of a given Company Name. If we write the Test using then() passing a reusable function, which looks like below.
Now if we execute this test, it will fail.
The reason for this is then() will not be retried.
So now in order to handle the use cases where we want to write reusable functions which queries the data we can use the Custom query, which can be written like below
If the query returning the data fails with using should() assertion, then whole query will be retried until the timeout. And if we execute this test which uses query, our test works now and passes.
Source code of this example can be found here https://github.com/gurudattgd04/cypress-example (Do not forget to give a star, so that it can reach out to many and helps others)