Cypress Test Cases Writing Take Aways.

Finally I setup Cypress for the project that I am working on in my company. After wrote several test cases, here is some take aways I want to share.

Stub Network Before Visit

When stubbing the requests for test cases, cypress need to know about the routes before the reqeusts being made from the app you are testing.

This is crucial for the initial requests that your app will emit to load initial data used to boot up.

One way to make sure that is always put the stubbing before the visit() call:

Execute Javascript Before The Page Resource Loads

In case of any front end local data mocking, for example, data from localstorage. If that data is used during the initialization (if the user has already logged in), we need to make sure the mocking job be done before any page resource being loaded and executed.

To do this, we just need to use the callback function of visit():

Query Child Elements

This is a very common process when locating elements on the page. Look at an example below, which is an screenshot from the project I’m working on:

So above is a filter list in our product. And in my test case I need to check if the filters selected all exist and are visible.

How to do that? If just using cy.contains('24.com') seems easy enough, but not practical, as there might be another element on this page (note that the screenshot is just part of the page) may contains the same text. So we need to lock it in just in that area.

To do that, we locate this “Include” section first:

According the HTML structure, the filter list and the section title share the same parent, so the parent should be the scope to search from:

The key magic here is the within() command, it scopes all subsequent cy commands to within this element. Useful when working within a particular group of elements.

Useful Should() Assertions

  • Test existence: .should('to.exist')
  • Test non-existence: .should('not.exist')
  • Test visibility should('be.visible') and should('not.visible')

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.