Tosca tester
Custom Commands in Cypress.io
As a robust test automation tool, Cypress is known for its ability to simplify complex test scenarios. However, Custom Commands open the door to even greater efficiency and adaptability. In this article, we’ll explore together how Custom Commands can make your testing work easier.
What are Custom Commands?
Custom Commands in Cypress are essentially commands that extend or customize basic Cypress functionality. These commands are defined by the user to match the specific needs of the test scenarios, and can be used in different tests without having to write the same code repeatedly.
Custom Commands work on the principle of encapsulation: you wrap a complex set of commands or routine operations into a single custom function. This function is then called within your tests like any other command in Cypress. This means you can have a simple command that performs multiple actions at once.
For example, if you have a web application where you frequently test the login process, you can create a Custom Command for this process. This command will contain all the steps necessary to log in – filling in the login form, clicking the button and verifying the successful login. You can wrap all this into one command and then use this command in all tests where you need to verify the login process.
Why use Custom Commands?
Simplified test code
With Custom Commands, you can encapsulate complex and frequently used functions into simple, reusable blocks. This simplification will save you time and make your job easier when writing and reading tests.
Improved code maintenance
When it comes to editing or expanding your tests, Custom Commands let you make changes in one place. This way, the changes will automatically be reflected in all tests that use the command.
Better test organization
Custom Commands allow you to systematically organize and categorize repetitive tasks. This not only makes your test code more efficient, but also easier to understand for you and your colleagues.
Accelerated development cycle
Since Custom Commands reduce the amount of code written and make it easier to maintain, the overall time spent testing is significantly reduced. This is especially important in agile development environments where speed and flexibility are paramount.
Cypress testing and creation of Custom Commands
1. Define the command in the commands.js file:
Before you start defining your own commands, you need to make sure you have the right environment set up. Custom Commands are usually defined in the commands.js file found in the cypress/support directory. So you can start adding custom commands in the commands.js file. To add a custom command in Cypress, the Cypress.Commands.add() method is used. Here’s an example of how to create a basic Custom Command to log in:
Cypress.Commands.add('prihlasenie', (email, heslo) => {
cy.get('input[name=email]').type(email);
cy.get('input[name=password]').type(heslo);
cy.get('button[type=submit]').click();
});
In this example, we have created a Custom Command called login that expects two parameters: email and password. This command fills in the login details and then clicks to submit the form.
2. Use Custom Command in testing
After defining Custom Command, you can start using it in your tests. Here is an example test that uses the Command Login defined above:
describe('Prihlasovací Test', () => {
it('úspešné prihlásenie do systému', () => {
cy.visit('/prihlasenie');
cy.prihlasenie('test@example.com', 'heslo123');
// Tvoj ďalší testovací kód...
});
});
In this test scenario, we will visit the login page and use our Custom Command login to fill out and submit the login form.
Overwriting existing commands in Cypress
When working with Cypress, you may encounter a situation where you need to modify the behaviour of existing commands to better suit the specifics of your project. It’s important to understand that Cypress allows you not only to add your own commands, but also to overwrite existing ones. This is very useful when you want to set some defaults and avoid creating new commands that just replicate the original functionality.
Cypress.Command.overwrite() allows you to overwrite an existing built-in command or reserved internal function.
A good example of using Cypress.Commands.overwrite might be in a situation where you need to ensure that specific rules or settings are followed for all tests within your application. For example, if you want to change the behaviour of cy.click() so that it always verifies that the element being clicked is visible and available to the user.
Cypress.Commands.overwrite('click', (originalFn, subject, options) => {
// Najprv over viditeľnosť elementu
cy.wrap(subject).should('be.visible');
// Potom vykonaj pôvodný príkaz click s pôvodnými argumentmi
return originalFn(subject, options);
});
In this example, before each execution of cy.click(), your modified version of the command first checks that the element to be clicked is visible. This helps prevent errors in tests that could occur if they attempt to interact with invisible or otherwise inaccessible elements. The use of overwrite in this context increases the robustness and reliability of the tests, ensures consistent behaviour, and eliminates the need to repeat this check in every single test.
Custom Commands best practices
The following recommendations will help you maximize their effectiveness while keeping your test code clean and sustainable:
1. Use custom commands selectively
Custom commands are an effective solution when certain operations need to be standardized across the entire spectrum of tests. Typical examples are commands such as cy.setup() or cy.login(), which extend the functionality of an application based on specific needs. Nevertheless, it is important to avoid excessive use of this option. Writing tests in Cypress relies on JavaScript, and it is often more efficient to define functions for specific operations that are relevant only to a particular test suite.
2. Avoid excessive complexity
Writing custom commands means creating abstractions over a series of internal commands. This approach can lead to overcomplication and increased mental effort for you and your team when trying to understand the functionality of these commands.
For example, creating a command like cy.clickButton(selector).shouldBeVisible() is basically just wrapping simple commands like cy.get(selector).click(). This path can lead to creating a large number of custom commands that cover every possible interaction with elements, which is unnecessary.
3. Limit the functionality of individual commands
When creating custom commands, it is important to keep them simple and modular. Cramming a large amount of functionality into a single command leads to inflexibility and increases the need to traverse multiple options to control their behaviour.
4. Minimize dependency on AI
Using custom commands to abstract application settings and configurations is effective, but it is important to minimize dependency on the user interface. Where possible, it is recommended to use direct API calls or cookie handling and localStorage. This approach achieves a significant speed-up of testing and simplification of code.
5. Keep code clean and organized
Regular maintenance and review of your own orders is key. Make sure your commands are well documented and easily understood by other members of your team.
Conclusion
Custom Commands in Cypress are a powerful tool that allows you to write more efficient and sustainable tests. Experiment with them and see how they make your job easier and your application testing process more efficient. Remember that practice is the key to success, so get going and enjoy the benefits Cypress has to offer. Good luck!
If you speak German and are an IT tester or IT automation tester, take a look at our employee benefits and respond to our latest job offers!