11 best practices for Cypress Automation

binaya dhungana qa engineer
Binaya Dhungana
QA Engineer

Faster and more efficient QA testing enables new, high-quality products and features to reach the market sooner. For that reason, there are many tools and technologies on the market that support the automation of Quality Assurance (QA). 

From a technical perspective, the challenge is how to optimize QA testing processes to ensure they are robust, streamlined, and more efficient. Here at Proshore, we use Cypress as part of our Continuous Improvement / Continuous Delivery (CI/CD) model. Here are 11 best practices for Cypress automation based on our knowledge and experience.

1️⃣ Centralize page URLs

In Cypress automation for UI testing, verifying URLs is crucial to confirm the expected redirection of scripts. To manage numerous URLs efficiently, it’s a good idea to consolidate them into a single file in a centralized repository.

Storing all URLs in this way simplifies updates and minimizes the risk of errors. Taking this structured approach also helps ensure effective management and maintenance of automation URLs. Following this practice also provides consistent automation results.

2️⃣ Store login credentials in a constant file 

Rather than hard-coding logins within the test specifications, it makes sense to keep them within a constant file. Users can be role-based, normal, or admin. Centralizing login credentials simplifies management and updates, reducing maintenance efforts.

Storing credentials in a constant file enhances the reliability and stability of automation tests. It also ensures consistent usage across all tests. That’s because a constant file with login credentials can be easily reused, minimizing code duplication and errors. There’s no need to write (and update) multiple users across different places – everything is held in one place. 

3️⃣ Improve selector management 

All too often, Cypress test picks are written ‘cy.get(‘selector’)’ followed by the type action required. This isn’t a practical or efficient approach when the same selectors have to be used in multiple places. 

Instead of rewriting for common elements like pop-up modal or search filter multiple times, it’s much more efficient to create one common class, keeping all the selectors in the same place. Now, selectors can be reused in multiple different places, making it much easier to debug and fix.

4️⃣ Always implement a POM logger

Sometimes, when a class containing certain selectors and actions is recalled, it’s unclear as to which method or class has been called. When debugging test cases, if a failure is found, every line of code will need to be checked.    

Creating a page class means functionality can be easily reused in other pages. Cypress supports Page Object Model (POM) and by using a POM Logger it’s possible to capture and record information during test automation.

A POM Logger captures page navigation, element interactions, validations, and exceptions.

The logged information can be directed to various output destinations for analysis and troubleshooting.

5️⃣ Ensure uniformity in naming conventions 

Naming conventions in Cypress are an agreed set of rules for naming variables, functions, and files. Following consistent naming conventions make it much easier to maintain and understand the code, facilitating a smoother and more efficient development process. 

For example, you could use PascalCase or camelCase to name the files. Variable names could use camelCase and function names could use PascalCase. Ensuring this uniformity of writing test codes improves readability for the entire team. 

At the same time, test cases should have descriptive and meaningful names beginning with ‘should allow <personas>…’ followed by a clear action such as ‘create a sign-up’. This also makes the purpose of the code clearer to non-technical stakeholders. 

6️⃣ Streamline testing with test splitting

Whilst it’s possible to create long test scripts with hundreds of lines of code, in practice it’s much easier to maintain, update, and debug smaller tests. Splitting code into blocks of 10 to 20 lines has a number of advantages. 

Breaking down long tests into smaller units allows for faster feedback and early issue detection during the development cycle. It also provides a clear view of the tested functionality, facilitating issue identification and isolation. At the same time, running smaller tests in parallel reduces the overall test suite execution time. 

Smaller tests offer reusability, as they can be utilized in multiple test cases, reducing code duplication. Using smaller tests also improves the organization of the test suite, making it much easier to locate and execute specific tests. 

7️⃣ Optimize input management

Automation requires a lot of input data to check that the correct actions are being performed. With a constant file, all user inputs can be stored in a single location to make it easier to manage and maintain the data. 

By storing user inputs in this way, it’s possible to ensure that the same data is used across different test cases, improving consistency, and reducing the risk of errors. If a user input needs to be updated, the change only needs to be made once, and it’s updated everywhere.

8️⃣ Create more efficient queries 

The actions performed by cy.get and cy.contains are very similar. However, the cy.contains method uses partial text matching to select elements. This can lead to unreliable selectors.

On top of that, it can slow down test performance as it searches through all the elements on the page to find a match.

The cy.contains method also has limited functionality compared with the cy.get method, making it less flexible and versatile. That’s because the cy.get facilitates more precise selector targeting using CSS classes, IDs, or other attributes, making it a better choice for complex testing scenarios.

9️⃣ Don’t wait – take a timeout 

Sometimes during the execution, there may be a need to hold back while a certain event completes. Cypress gives you the option to cy.wait, but this can lead to failures and problems with excess memory usage.  

To avoid this problem, and gain precise control over the waiting time, the best practice is to use cy.timeout. This ensures that your tests aren’t held up longer than necessary. This can help to speed up the test suite. It also makes the test code more readable, so it’s far easier to understand what’s happening. 

By reducing the load on the system, it’s possible to improve the overall performance of your tests, making them faster and more reliable. The great thing about timeouts is that they’re really easy to implement in your test code, so you can start seeing the benefits right away. 

1️⃣0️⃣ Empower API interception with clock and tick

API Interception is the process of capturing and modifying API requests before they reach the actual API endpoint. This is done to test the application’s behavior in response to different API request scenarios.

In Cypress, the cy.intercept function is used to capture API requests and modify their response before they reach the actual API endpoint. For precise timing of API requests, cy.clock can manipulate the system clock. It can also isolate the latest response and avoid overlapping request issues. Meanwhile, the cy.tick function enhances control over API request timing by advancing the clock by specified milliseconds. 

To avoid ‘race conditions’, and ensure accurate test execution with expected results, the best practice is to combine cy.wait with cy.clock.

1️⃣1️⃣ Standardize and improve code quality 

Ensuring consistent code quality across multiple developers is no easy feat – especially when you have a large development team. That’s where tools such as Eslint, Husky, and Prettier come in handy. 

Eslint is a linting tool for JavaScript that imposes a consistent code style and prevents common mistakes. On the other hand, Husky helps automate tasks (such as linting) before code is committed. It helps create a clean and stable codebase with fewer bugs.

QA Automation From Proshore

Here at Proshore, we provide cost-effective, highly-skilled, and ready-to-code development teams to software companies around the world. Not only do we help bring their software to life, but we also play an active role in quality assurance, with our highly-trained QA and QA automation engineers. In fact, our CI/CD has robust QA practices – and Cypress – built in as standard, to ensure we deliver high-quality web applications. 

Interested in becoming a QA Automation Engineer with Proshore? View our current career opportunities.

4 minutes

The cost of hiring dedicated Laravel developers

A popular PHP framework behind many web apps we see and use today – but what is the cost of development for projects built using Laravel?
Customer Success
Team
7 minutes

11 benefits of Laravel and multi-tenant architecture for SaaS

Laravel gives both developers and the software companies they serve many strategic advantages. Here’s how it can benefit multi-tenant SaaS.
Customer Success
Team

How Proshore is improving Shopify app performance using Laravel microservices

Our developers integrated legacy CMS with the power of Laravel microservices to improve Shopify app performance. Here’s how and why.
Customer Success
Team