In Cypress, waiting for custom commands to complete before proceeding with the remaining commands is a common requirement. Cypress's command queue mechanism inherently supports sequential command execution. When defining a custom command, you can ensure execution order by returning a Cypress command or a Promise. Here are examples of how to achieve this:
Example 1: Using Cypress Commands
Suppose we have a simple custom command that performs DOM operations, and we ensure subsequent commands execute only after this operation completes:
javascript// Define custom command Cypress.Commands.add('customCommand', () => { return cy.get('.element').click(); // Returns a Cypress command }); // Use custom command cy.customCommand() .then(() => { // This part executes after customCommand completes cy.get('.nextElement').should('be.visible'); });
In this example, cy.get('.element').click() is an expression that returns a Cypress command. This means cy.customCommand() returns a Promise-like object, and Cypress automatically handles the completion state before proceeding to the next command in the chain.
Example 2: Using Promise
If your custom command involves asynchronous operations, such as API calls, you can use the new Promise structure to ensure asynchronous behavior is properly handled:
javascript// Define an asynchronous custom command Cypress.Commands.add('customAsyncCommand', () => { return new Promise((resolve, reject) => { setTimeout(() => { // Assume this is the code after the asynchronous operation completes resolve(); }, 2000); }); }); // Use custom command cy.customAsyncCommand().then(() => { // This part executes after customAsyncCommand completes cy.get('.afterAsync').should('be.visible'); });
Here, new Promise ensures Cypress waits for the Promise to fully resolve before executing subsequent commands, even for asynchronous operations.
Summary
Through these examples, it is evident that whether directly returning a Cypress command or using Promise to manage asynchronous operations, Cypress's mechanisms guarantee sequential command execution. This is crucial for maintaining test reliability and predictability.