Abiral Sthapit

Maintainable Tests — Cypress.io

Writing tests in cypress are very easy and in no time we can write blocks of test code consisting of hundreds of tests. Tests are written for failure cases and because it is so simple one doesn't consider what if the test failed or tests needs to be changed. A well written tests should always help to understand what failed and should be maintainable in future.

Cypress provided us some neat key tips on improving the test code quality, read Best Practices from the cypress documentation, moving forward from this are

Each Test Must Be Isolated

By default cypress split the test file from file level, so at minimum a test file should not rely on any state from previous test file, but a test can also fail at any step, and each it block is run regardless of previous it block so if one it block relies on the state from previous it block, cascading failures can happen which later can be difficult to understand.

Example:

Assertion Should Be Concise

A common problem when using cypress test is expecting something to be true which will leads unclear assertion failure. Cypress Assertion lists out all the assertions. A good practice is to make the test fail first and check if the error message is enough to know why it failed.

Example:

Limiting The Code Redundancy

Lets see the first rule, by isolating the tests and breaking them into smaller individual tests does help with unwanted cascading failures but it will also bring a lot of redundant code. For a large project you might have lot of UI components that are re-used (Theme based components). we do not want to change all the tests across different page if one of the design for the component changes. For a easier E2E test, we can ship if all the functionality are working as expected.

Even though cypress is against POM pattern, by using POM we can minimize the refactor needed for above kind of changes and plus it will also provide a good looking testcases that are easier to understand.

Example:

POM for home page consists of basic actions and some unique element that we may need in future for further verification.

Page index for the file so in future if any of the page needs to be changed the test code doesn’t need to be changed

Finally the tests that consist of mainly behavior for user’s actions.