21 May 2024 Leave a comment Tech-Help
Creating custom commands in Cypress can significantly enhance the efficiency and readability of your tests. However, users sometimes encounter issues where custom commands are not recognized when invoked. This guide will walk you through a common solution to this problem and ensure your custom commands are correctly recognized by Cypress.
Understanding the Issue
When you move functionality to a custom command in cypress/support/commands.js
, you might encounter an error message stating: TypeError: cy.login is not a function. This typically happens because the custom command is not loaded properly.
Solution
To ensure your custom commands are recognized, follow these steps:
1. Import Commands in index.js
Ensure that your custom commands file is imported in the cypress/support/index.js
file. This file is loaded before any test files are evaluated, making the commands available globally.
// cypress/support/index.js
import './commands';
2. Check Your Configuration
Verify that the supportFile
property in your cypress.json
is not set to false
. This property should either be omitted or set to the correct path if you are using a custom support file path.
// cypress.json
{
"baseUrl": "http://demo.your-domain.test",
"supportFile": "cypress/support/index.js" // Ensure this line is correct
}
3. Wrap Commands in a Function (If Necessary)
If you are still encountering issues after following the above steps, consider wrapping your Cypress.Commands.add
calls in a function and then importing and executing this function in your index.js
file.
// cypress/support/commands.js
export default function addCustomCommands() {
Cypress.Commands.add('login', (username, password) => {
cy.request({
method: 'POST',
form: true,
url: '/test/login/',
body: { 'username': username, 'password': password }
});
});
}
// cypress/support/index.js
import addCustomCommands from './commands';
addCustomCommands();
Conclusion
By following these steps, you can ensure that your custom commands are properly recognized and loaded in Cypress. This will help you maintain cleaner and more efficient test scripts.
Enhance Your Testing with Repeato
If you are looking for a no-code solution to further streamline your testing process, consider using Repeato. Repeato is a powerful test automation tool for iOS and Android that allows you to create, run, and maintain automated tests with ease. It features an intuitive test recorder and supports advanced scripting for complex use cases.
With Repeato, you can quickly edit and run tests, leveraging computer vision and AI to ensure accuracy. Additionally, Repeato supports testing websites within an Android emulator or device, with explicit web testing support coming later this summer.
For more information, visit our documentation or contact us for support.