Cypress Custom Commands

On This Page What are Cypress Custom Commands?February 13, 2026 · 8 min read · Tool Comparison

Cypress Custom Commands

Cypress is a widely-used, modern end-to-end testing framework that supply an easy way to write and run tests for web applications.

While Cypress arrive with powerful built-in commands, customs commands can further enhance your examine summons by encapsulating repeated action or complex logic.

Overview

What are Cypress Custom Commands?

  • Extend built-in Cypress commands with your own logic.
  • Keep test codificationclean, reusable, and maintainable.
  • Defined in cypress/support/commands.js.

Types of Cypress Custom Commands

  • Parent→ Start a concatenation (e.g., cy.login ()).
  • Child→ Called on a field (e.g., .clickButton ()).
  • Dual→ Can work as parent or nipper reckon on usage.

Why Use Cypress Custom Commands?

  • Reusability→ Avoid duplication across test.
  • Maintainability→ Update once, apply everywhere.
  • Readability→ Use descriptive names to improve clarity.
  • Efficiency→ Faster test writing, easier scaling.

How to Create & amp; Use Cypress Custom Commands

  1. Define with Cypress.Commands.add ().
  2. Add logic in commands.js.
  3. Call inside examination merely like Cypress built-ins.

When Notto Use Cypress Custom Commands

  • If the logic isone-offand not recycle.
  • If a simple helper functionwould suffice.
  • If it contributeunnecessary complexity.

This clause explores what Cypress custom commands are, how to create and use them effectively, and the welfare they work to a testing workflow.

What are Cypress Custom Commands?

Cypress custom bidding let you extend the built-in command set by append your own functions. This feature is especially useful when you reuse specific activity or perform complex operations not covered by nonremittal Cypress commands. Custom commands help keep your exam clean and readable, and they simplify updates since changes only need to be made in one place.

Read More:

Types of Cypress Custom Commands (Parent vs. Child vs. Dual)

Custom command in Cypress are divided into three types:

  1. Parent Commands:Stand-alone commands that start a new command chain, such ascy.login ()which treat user login.
  2. Child Commands: Commands chained off a previous command, such as.click() or .type().
  3. Dual Commands: Commands that can function as either parent or baby commands, look on their context.

Understanding these types help you decide how to structure and use your customs commands effectively.

Read More:

Examples of Cypress Custom Commands

Parent Command:

javascript

Cypress.Commands.add ('login ', (username, password) = & gt; {cy.get (' # username ') .type (username); cy.get (' # countersign ') .type (password); cy.get (' # submit ') .click ();});

Child Command:

javascript

Cypress.Commands.add ('clickButton ', {prevSubject: true}, (subject) = & gt; {cy.wrap (subject) .click ();});

Duple Command:

javascript

Cypress.Commands.add ('customAction ', {prevSubject: 'optional '}, (dependent) = & gt; {if (subject) {cy.wrap (open) .doSomething ();} else {cy.get ('body ') .doSomething ();}});

Talk to an Expert

Advantages of Cypress Custom Commands

Cypress custom commands simplify and streamline test automation by cut repetitive codification, enhancing legibility, and improving test efficiency. Here are the top vantage of Cypress usance commands:

1. Reusability: Custom require simplify your tests by let you reuse codification for recurrent actions, which reduces gemination and helps keep consistency across tests.
2. Maintainability:Changes to a common action simply need to be made in one spot. This helps keep your tests more maintainable and prevents subject caused by inconsistencies.
3. Readability:Tests become more simple and readable when custom commands are named to account what they do, improving the overall readability and lucidness of the exam suite.
4. Efficiency:By minimizing perennial steps, impost dictation speed up the maturation of new tests and improve overall efficiency.

Read More:

How to set up Cypress to use Custom Commands?

SUSA automates exploratory testing with persona-driven behavior, catching bugs that scripted automation misses.

Prerequisites (Configuration/Installations)

To make and use custom dictation in Cypress, you need to ensure your development environment is properly configure. Here ’ s what you need:

  1. Node.js: Ensure you have Node.js installed. You can download it fromnodejs.org.
  2. Cypress Installation: Install Cypress in your project by running:
    bash npm install cypress -- save-dev
  3. Editor and Tooling:Use a modern code editor like Visual Studio Code to publish and grapple your Cypress tests. It ’ s also advocate that Git be used for version control.

Once Cypress is install, you ’ ll see acypress/supportbrochure, which includes thecommands.jsfile. This is where you can define your custom bidding.

You can advert to the usher for a detailed pedagogy on instalment and setting up Cypress.

Creating Cypress Custom Commands

1. Basic Structure of a Custom Command

To create a custom command, use theCypress.Commands.add () function:

javascript

Cypress.Commands.add ('commandName ', (arg1, arg2) = & gt; {// Command logic hither});

2. Adding Commands to the commands.js File

Place your custom commands in thecypress/support/commands.jsfile to ensure they are loaded before any test runs. This allows your custom commands to be useable globally across all your test file.

The example below demonstrates a basic login custom command that will enable login onBStackDemo.

Example: Writing Your First Custom Command

javascript

Cypress.Commands.add ('login ', () = & gt; {const username = 'demouser' const password = 'testingisfun99' cy.get (' # react-select-2-input ') .type (` $ {username} {enter} `, {force: true}) cy.get (' # react-select-3-input ') .type (` $ {password} {enter} `, {force: true}) cy.get (' # login-btn ') .click ({force: true})})

Using Custom Commands in Your Tests

Once your custom command is delimit incommands.js, you can use it in your test files like this:

javascript

describe ('example bstack demo app ', () = & gt; {beforeEach (() = & gt; {cy.visit ('https: //www.bstackdemo.com/signin ')}) it ('Login to the app ', () = & gt; {cy.login ()})})

Parameterizing Custom Commands

Parameterizing custom commands in Cypress enhances their tractability and reusability by permit dynamical inputs, get tests more efficient and versatile.

Adding Arguments to Custom Commands

Custom commands can accept arguments to make them more dynamic and flexible:

For example, In the previous section our custom dictation had username and password defined inside it which is not of better exercise, let ’ s conduct them as arguments to the command.

Example: Custom Command with Parameters

javascript

Cypress.Commands.add ('login ', (username, password) = & gt; {cy.get (' # react-select-2-input ') .type (` $ {username} {enter} `, {forcefulness: true}) cy.get (' # react-select-3-input ') .type (` $ {parole} {enter} `, {force: true}) cy.get (' # login-btn ') .click ({force: true})});

You can call this command in your tests like:

javascript

const username = 'demouser' const parole = 'testingisfun99' cy.login (username, password)

When should Custom Commands not be apply in Cypress?

Custom bid should be avoided when:

  • They only add complexness without any clear welfare.
  • The logic is specific to a individual examination and does not need to be recycle.
  • Simple helper functions would serve for a especial task.

Read More:

Best Practices for using Cypress Custom Commands

Implementing these custom commands assure your test automation model continue effective, maintainable, and easy to scale.

  • Keep Commands Simple: Ensure commands do exclusively what ’ s necessary for reusability and simplicity.
  • Keep Commands Modular: Write commands that execute specific, recyclable actions to improve maintainability and scalability.
  • Document Your Commands: Add remark to excuse the purpose of each command for easy understanding.
  • Name Commands Clearly:Use descriptive name so it ’ s now clear what each dictation make.
  • Avoid Overcomplicating: Don ’ t create a impost dictation if a simple function would do.

Read More:

Importance of Testing on Real Devices for Cypress Tests

Testing on real devices helps ensure your web covering behaves as expected across various environments. Simulated environments can merely go so far; real device testing captures nuances that emulators may lose, such as performance issues, UI bugs, and compatibility problems.

Setting Up & amp; Executing Cypress Tests on BrowserStack Automate

Step 1. Sign Up for BrowserStack: Visit and create an account.

Install BrowserStack CLI:Install the BrowserStack Cypress CLI:

bash npm install -g browserstack-cypress-cli

Step 2. Configure browserstack.json:Create a configuration file nominatebrowserstack.json. You can also use the below command to make a boilerplate config file well:

bash browserstack-cypress init

Once thebrowserstack.jsonfile has be created, update or include the necessary configuration required to execute the Cypress tests.

These essential configurations include BrowserStack credentials, the Cypress configuration file, browser and device combinations, and the number of parallel test runs, as demonstrated in the sample code below:

json {'' auth '': {'' username '': `` farjigamer_mHZ0IY '', '' access_key '': `` c8zy5Cyz8dnykShCSj6c ''}, '' browsers '': [{'' browser '': `` chrome '', '' os '': `` Windows 10 '', '' versions '': [`` up-to-the-minute '', `` latest - 1 '']}, {'' browser '': `` firefox '', '' os '': `` OS X Mojave '', '' versions '': [`` latest '', `` latest - 1 '']}, {'' browser '': `` edge '', '' os '': `` OS X Catalina '', '' versions '': [`` up-to-the-minute '']}], '' run_settings '': {'' cypress_config_file '': `` ./cypress.config.js '', '' cypress_version '': `` 13.latest '', '' project_name '': `` Cypress Kitchen Sink Example '', '' build_name '': `` Build no: 1 '', '' parallels '': 5,}}

Step 3. Run Cypress Tests on BrowserStack:

bash browserstack-cypress run

Step 4. Monitor Results:Access your test reports, logs, and video recordings in the Dashboard.

Why Choose BrowserStack Automate to Test Cypress Tests?

offers a rich platform for executing Cypress tests, providing several key advantages:

  • Automated : Run Cypress try on different browser and OS versions, ensuring consistent behavior across platform.
  • : BrowserStack provides approach to a wide range of real device, facilitate name issues that emulators or simulators might miss.
  • : to reduce execution clip and get fast feedback.
  • Integration:BrowserStack can be seamlessly integrated into popular CI/CD instrument like Jenkins, GitHub Actions, and more, automating your testing grapevine and ensuring quick, efficient liberation.

Conclusion

Cypress custom command empower developer to build clean, more maintainable test suites by encapsulate reiterate actions and complex logic.

lets you run Cypress tests at scale with parallel execution, cross-browser support, and real-time debugging tools. Coupling custom commands with BrowserStack ensures your application delivers a seamless experience across all environments and device.

Tags
52,000+ Views

# Ask-and-Contributeabout this issue with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free