Custom Commands | Bondar Academy
Course: Cypress UI Testing with JavaScript
Module: Page Object Design Pattern
Instructor: Artem Bondar
Lesson Summary
In this lesson, we explore Cypress custom commands , which allow you to create reusable commands that can be called globally in any test or spec file. Creating Custom Commands Custom commands are defined in the commands.js file located in the support folder. The syntax for creating a custom command is as follows: Cypress.Commands.add('commandName', (args) => { // command body }); For example, to create a command for opening the home page: Cypress.Commands.add('openHomePage', () => { cy.visit('/'); }); Using Custom Commands Once defined, you can call the custom command in your tests simply by using: cy.openHomePage(); Limitations of Custom Commands IntelliSense Limitations: Custom commands do not appear in IntelliSense suggestions, making it harder to discover them. No Navigation: You cannot navigate directly to the implementation of a custom command from your test files. Improving IntelliSense To enhance IntelliSense for custom commands, create a new namespace and interface in a separate file: declare namespace Cypress { interface Chainable { openHomePage(): Chainable ; } } This allows for better recognition of custom commands in your IDE. Best Practices Use custom commands for global operations that are frequently needed across tests. Avoid creating too many custom commands to maintain clarity and ease of navigation. For specific functionality, prefer using JavaScript functions or methods instead. In summary, custom commands are powerful tools in Cypress, but should be used judiciously to maintain an organized and efficient testing framework.