SDET Unicorns

Cypress Custom Commands: Enhance Your Test Automation Suite !

Cypress Custom Commands

Table of Content

In the world of web development and software testing, automated testing tools have become indispensable. They help ensure that web applications function correctly and consistently across different browsers and platforms while facilitating and reducing the cost of regression testing. Cypress.io is one such automation tool that has gained significant popularity due to its simplicity, speed, effectiveness, and user-friendliness. 

One of the standout features of Cypress is its ability to create Custom Commands, which can greatly enhance the efficiency and maintainability of your test suites and enable you to edit them to your liking and needs.

In this article, I will dive deep into Cypress Custom Commands, exploring their purpose, and benefits, while sharing with you how to create and use them effectively with your test suite.

For those looking to get started with Cypress, here’s an Awesome YouTube playlist to guide you.

Pre-requisites:

  • Base knowledge of Cypress
  • Eager to learn useful stuff 😉

What is Cypress?

cypress custom demand

Before we dive into the specifics of Cypress Custom Commands, it’s important to understand what Cypress is and why it has become such a popular choice for QA Engineers.

Cypress is an end-to-end testing framework that provides a fast, reliable, and intuitive way to write and run tests for web applications across all major browsers. Unlike traditional testing tools, Cypress operates directly in the browser using DOM events, which gives it several advantages:

  1. Real-Time Feedback: Cypress provides real-time feedback as you interact with your application, making it easy to Debug and resolve issues quickly.
  2. Automatic Waiting: It automatically waits for elements to appear and become interactable, eliminating the need for manual “awaits” or sleep statements in your test code.
  3. Time Travel: Cypress allows you to see what your application looked like at any point during the test (it’s called Snapshots), making debugging more straightforward.
  4. Easy Debugging: You can pause the test at any point, inspect the application, and even modify its state, which is immensely helpful for debugging.
  5. Automatic Reload: Cypress automatically reloads the page when needed, ensuring that your tests remain in sync with your application.

These features, among others, make Cypress a compelling choice for web application testing.

However, Custom Commands are essential to harness its full potential.

What Are Cypress Custom Commands?

Cypress Custom Commands are functions defined by the developer / QA Engineer that extend the capabilities of Cypress’ API. In other words, they are like little blocks that you create to encapsulate a sequence of actions that you use frequently in your tests (Login, hovering, etc.). Encapsulating these actions or assertions into commands will make your test code more readable, easier to maintain, and reusable.

Let’s take a practical example to illustrate the concept of custom commands:

Suppose you frequently need to log in to your web application for various tests. Instead of duplicating the login code in every test, you can create a custom command called login that encapsulates the login process and call the command where needed. This not only reduces code duplication but also makes your tests more concise and easier to maintain.

Using Cypress Custom Commands

using cypress commands

There are two APIs available for adding custom commands:

  • Cypress.Commands.add(): used to add a new custom command to use when writing tests
  • Cypress.Commands.overwrite(): used for overwriting overwrite existing commands.. Keep in mind that this overrides it for Cypress as well and could impact how Cypress behaves, so use it with caution.

Start by installing Cypress as a dev dependency in your project using :
				
					npm install cypress --save-dev 
npx cypress open 
				
			

Now, you should have a project containing multiple folders such as e2e, plugins, support, etc.

 

Important

Your own Custom Commands need to be written in the cypress/support/commands.js folder.

 

 Commands Syntax: 
				
					Cypress.Commands.add(name, callbackFn)
Cypress.Commands.overwrite(name, callbackFn)
				
			

name (String): the name of the custom command you’re creating (Example: “Login”)

callbackfun (Function): a callback Function that receives the argument to pass to the custom command

 

Real Examples: 

1- Let’s suppose you need to click lots of links in your test automation project, you would need to do each time something like: 

				
					cy.get('a').contains(label).click()
				
			

You can do this by adding a new Custom Command Cypress Commands add: (“label” being your test data)

				
					// cypress/support/commands.js

Cypress.Commands.add('clickLink', (label) =>; {
  cy.get('a').contains(label).click()
})
				
			

Now, whenever you need to click a link anywhere in your project you can do it this way:

				
					cy.clickLink("Join Academy")
				
			

 

2- Imagine your team’s developers implemented in each HTML element a unique ID to use in your test and they named it “testElementId”. Of course, that is a great thing, now you don’t have to worry about locating elements. 

This is how you would get each element:

				
					cy.get('[data-testelementid=label]')

// real world one: 
cy.get('[data-testelementid=join_academy_button]')
				
			

Quite long isn’t it? 

				
					Cypress.Commands.add("byTestId", (id) =>; {
    cy.get(`[data-testelementid = '${id}']`)
})

// Usage :
cy.byTestId("join_academy_button")
				
			

See how it’s better in all aspects when you make it a Custom Command?

Now whenever you want to locate an element by its custom ID you only use that tiny function 🙂

 

3- Say that you need to perform lots of login actions throughout your tests.
To perform a login action you need to:

– Get the email input and write the email

– Get the password input and write the password

– Get the login button and click on it

You can merge all those steps in the same custom command like this:

 

				
					Cypress.Commands.add("login", (email, password) => {
    cy.get("#email_input").type(email)
    cy.get("#password_input").type(password)
    cy.get("#login_button").click()
    cy.contains("Login").should('not.exist')
    cy.getCookie("auth_key").should('exist')
})
				
			

This Custom Command takes 2 parameters: email, and password, and enables you to locate, type text, and click on the login button. Then, it checks that the “Login” button does not exist to make sure we are redirected to the logged-in UI, and it also checks for the existence of the “auth_key” cookie which is a cookie that we attribute to each user after he logs in.

Using it is even easier:

				
					cy.login("SDET_Expert", "CheckOurCourses123")
				
			

4- Logging in via the UI is not the optimal way, if you have a repetitive Login scenario then you should do it via API!

 

				
					Cypress.Commands.add("loginAPI", (email, password) => {
    cy.request({
        url: '/login',
        method: 'POST',
        body: {
          email: email,
          password: password,
        },
     })
     cy.setCookie("auth_key", response.body.auth_key)
     cy.reload() // or cy.visit("/")
     cy.contains("Login").should('not.exist')
})
				
			

Now what I did here is:

– Send a POST request to the Login API with the body containing the required parameters.

– Set the “auth_key” cookie manually because since we are not using the UI, it is not done automatically.

– Refresh the page to see the changes apply.

– Assert that we are redirected to the logged-in UI.

If you have lots of logging-in in your steps I strongly advice to do it via API since it is much much faster.

5- Cypress does not have a hover function that enables you to show popups, so, making it a custom command would be quite useful (I, personnally add it in all my projects as default commands): 

				
					Cypress.Commands.add("hover", (element) => {
    cy.get("element").trigger('mouseover')
})
				
			

6- Now it is your turn to code your own Cypress Custom Command! 

Quick exercise: 

– Add a Custom Command that enables you to Logout through the UI, knowing that the Logout button is on a modal that pops up when you hover over your avatar.
The solution will be at the very end of this article before the conclusion. DO NOT CHEAT ! 😉

Benefits of Using Cypress Custom Commands

benefits of using cypress commands

Now, you should have understood what a custom command in Cypress is, and how to make it work!

Let us see HOW it will benefit your automation project:

  1. Code Reusability: a Cypress Custom command helps you to reuse common testing steps across multiple test scenarios, which highly reduces redundancy and makes code clearer to read since you’re only calling a function.

  2. Improved Readability: When you encapsulate complex interactions into custom commands with good names that describe their usage, your whole test code becomes more readable and easier to understand for everyone.

  3. Maintenance Ease: When your application’s UI (User Interface) changes, you only need to update the locators in the custom command rather than making changes in all the files you’re using them. That is highly efficient when you’re working on an application that keeps growing.

  4. Faster Test Development: Well-made custom commands give you the ability to write tests faster and with a higher coding velocity since you can leverage the commands that you defined for repetitive actions, such as logging in, logging-out, navigating between pages, and interacting with different elements in the UI.

Exercise solution: 

				
					Cypress.Commands.add("logout", (element) => {
    cy.hover(element)
    cy.contains("Log out").click()
    cy.contains("Login").should("exist")
})
				
			

Yes, you can nest existing commands! We used our previous command, just make sure the Hover command is defined before the logout custom command!

Conclusion

In Conclusion, we have seen what custom commands are, and how to create and use them in your project, and we clearly established that Cypress Custom Commands are obviously and without a doubt a powerful feature that you need to implement in order to enhance your test suite and project it to the next level.

By encapsulating your complex, common, and repetitive actions into custom and reusable functions, you have the power to create highly maintainable, efficient, and readable code while promoting consistency, reducing redundancy, and increasing the coding velocity of your team members.

In your continuous quest to be a master of Cypress, consider the specific needs of your application, Identify areas where custom commands can simplify your testing flow, and help you achieve your goals in test coverage and test efficiency so that you use them effectively and thoughtfully. You will see them become invaluable tools in your quest for a robust and reliable test automation project.

See you in the next one!

Do not forget to check all our Cypress articles, they are really valuable!

– Top 15 Cypress Interview Questions

– Setting up Cypress with Github Actions

– Automate OTP using Cypress

– Our Cypress Series !!

References

 

Frequently Asked Questions

You can a Custom Command using the Cypress Commands add function: Cypress.Commands.add()

A Custom Command is a function used to encapsulate repetitive tasks that you reuse throughout your test suite.

Custom Commands have to be defined in the “cypress/support/commands.js” folder

To use a custom command that you already defined simply use “cy.MyCustomCommand()” anywhere in your project

Only define Custom Commands when you have a repetitive task that takes too much time to write and that makes code less understandable and maintainable.

My Resources

Thrive Suite: The all-in-one WordPress theme I used to create my blog.
Jasper AI: My favorite AI writing tool.
Surfer SEO:  A tool to help you rank your content on the first page of Google.

Write Content Faster

5/5

Write blog posts that rank for affiliate terms!

Join our mailing list

Unlock the Secrets to Becoming a SDET Pro in the Industry!

Stay ahead of the curve! Join our mailing list for exclusive insights, tips, and the latest industry updates delivered straight to your inbox

Table of Content

Related Post

7 Principles of Software Testing

7 Principles of Software Testing with Examples

Software testing plays a crucial role in the software development life cycle as it helps ensure the quality, reliability, and performance of the final product. Software testing is not just about finding defects; it also provides valuable insights into the overall quality of the software. By conducting effective software testing, it shows how well the application behaves in different scenarios and whether it meets user expectations.

Read More »
Differences Between CI/CD and DevOps

Key Differences Between CI/CD and DevOps

Software development is far from a simple journey that involves merely executing code and launching applications. It often presents challenges, as it’s rare to get everything right from the start. Each time you implement new or frequent code changes, you inadvertently introduce potential issues that can be time-consuming to resolve. This complexity necessitates a structured approach to ensure smooth production.

Read More »