- 
                Notifications
    You must be signed in to change notification settings 
- Fork 1.1k
docs: Add best practices for element interaction patterns and command chaining #6242
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Open
      
      
            ziad404
  wants to merge
  11
  commits into
  cypress-io:main
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
ziad404:main
  
      
      
   
  
    
  
  
  
 
  
      
    base: main
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
  
     Open
                    Changes from 4 commits
      Commits
    
    
            Show all changes
          
          
            11 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      e4d802a
              
                Add best practices for element interaction patterns and command chaining
              
              
                ziad404 04f56d2
              
                Merge branch 'cypress-io:main' into main
              
              
                ziad404 0e56d9c
              
                Resolve lint issue
              
              
                ziad404 364846a
              
                After running prettier
              
              
                ziad404 2832dd8
              
                Merge branch 'cypress-io:main' into main
              
              
                ziad404 3485f0a
              
                Fixing the Added example
              
              
                ziad404 44cdd60
              
                fix: Correct syntax in best-practices.mdx code example
              
              
                ziad404 b0ba23a
              
                docs: Update command chaining examples to follow retry-ability best p…
              
              
                ziad404 87db512
              
                fix: Correct indentation in best practice example for form interaction
              
              
                ziad404 b4d3bc9
              
                fix: Improve formatting and readability in best practice examples for…
              
              
                ziad404 829e5ff
              
                fix: Simplify input field interaction example by consolidating commands
              
              
                ziad404 File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
|  | @@ -951,6 +951,184 @@ cy.wait('@getUsers') // <--- wait explicitly for this route to finish | |
| cy.get('table tr').should('have.length', 2) | ||
| ``` | ||
|  | ||
| ## <Icon name="angle-right" /> Element Interaction Patterns and Command Chaining | ||
|  | ||
| :::danger | ||
|  | ||
| <Icon name="exclamation-triangle" color="red" /> **Anti-Pattern:** Using `then()` | ||
| unnecessarily or re-querying the same element multiple times when chaining would | ||
| work. | ||
|  | ||
| ::: | ||
|  | ||
| :::tip | ||
|  | ||
| <Icon name="check-circle" color="green" /> **Best Practice:** Use command chaining | ||
| when possible, and only use `then()` when you need to perform complex operations | ||
| or work with the actual DOM element. | ||
|  | ||
| ::: | ||
|  | ||
| A common question arises when performing multiple actions on the same element: should you chain commands or use `then()` to wrap all actions? Let's examine the best approaches for common interaction patterns. | ||
|  | ||
| ### Multiple Actions on the Same Element | ||
|  | ||
| When you need to perform several actions on the same element (like focus, clear, type, and blur), you have two main approaches: | ||
|  | ||
| #### Option 1: Command Chaining (Recommended) | ||
|  | ||
| ```js | ||
| // RECOMMENDED: Chain commands when possible | ||
| cy.get('[data-cy="input-field"]').focus().clear().type('new value').blur() | ||
| ``` | ||
|  | ||
| #### Option 2: Using then() (Only when necessary) | ||
|  | ||
| ```js | ||
| // ONLY USE when you need to work with the actual DOM element | ||
| cy.get('[data-cy="input-field"]').then(($input) => { | ||
| cy.wrap($input).focus() | ||
| cy.wrap($input).clear() | ||
| cy.wrap($input).type('new value') | ||
| cy.wrap($input).blur() | ||
| }) | ||
| ``` | ||
|  | ||
| ### Why Command Chaining is Usually Better | ||
|  | ||
| **Performance Benefits:** | ||
|  | ||
| - Cypress optimizes chained commands and doesn't re-query the element unnecessarily. | ||
| - The element reference is passed through the command chain automatically. | ||
| - No additional overhead from `cy.wrap()` calls. | ||
|  | ||
| **Simplicity and Readability:** | ||
|  | ||
| - More concise and easier to read. | ||
| - Follows Cypress's natural command pattern. | ||
| - Less nested code structure. | ||
|  | ||
| **Automatic Retries:** | ||
|  | ||
| - Each command in the chain automatically retries if the element becomes stale. | ||
| - Cypress handles DOM updates and element re-querying automatically. | ||
|  | ||
| ### When to Use `then()` | ||
|  | ||
| Use `then()` only when you need to: | ||
|  | ||
| 1. **Access DOM element properties or methods directly:** | ||
|  | ||
| ```js | ||
| cy.get('[data-cy="input-field"]').then(($input) => { | ||
| const initialValue = $input.val() | ||
| // Do something with the initial value | ||
| if (initialValue !== '') { | ||
| cy.wrap($input).clear().type('new value') | ||
| } | ||
| }) | ||
| ``` | ||
|  | ||
| 2. **Perform conditional logic based on element state:** | ||
|  | ||
| ```js | ||
| cy.get('[data-cy="toggle"]').then(($toggle) => { | ||
| if ($toggle.hasClass('active')) { | ||
| cy.wrap($toggle).click() | ||
| } | ||
| }) | ||
| ``` | ||
|  | ||
| 3. **Work with multiple elements from the same query:** | ||
|  | ||
| ```js | ||
| cy.get('[data-cy="list-item"]').then(($items) => { | ||
| const count = $items.length | ||
| cy.log(`Found ${count} items`) | ||
|  | ||
| // Work with specific items | ||
| cy.wrap($items.first()).should('contain', 'First item') | ||
| cy.wrap($items.last()).should('contain', 'Last item') | ||
| }) | ||
| ``` | ||
|  | ||
| ### Common Misconceptions | ||
|  | ||
| **"Using `then()` prevents detached DOM errors"** | ||
|  | ||
| This is not accurate. Cypress automatically handles element re-querying in both chaining and `then()` scenarios. The framework is designed to handle DOM updates gracefully. | ||
|  | ||
| **"Element is found only once with `then()`"** | ||
|  | ||
| While `then()` captures the element at that moment, Cypress commands within `then()` (like those wrapped with `cy.wrap()`) still perform their own element queries and retries as needed. | ||
|  | ||
| ### Best Practice Examples | ||
|  | ||
| #### Form Interaction (Good) | ||
|  | ||
| ```js | ||
| describe('form interaction', () => { | ||
| it('updates input field correctly', () => { | ||
| cy.get('[data-cy="email-input"]') | ||
| .should('be.visible') | ||
| .focus() | ||
| .clear() | ||
| .type('[email protected]') | ||
| .should('have.value', '[email protected]') | ||
| .blur() | ||
| }) | ||
| }) | ||
| ``` | ||
|  | ||
| #### Conditional Actions (When `then()` is appropriate) | ||
|  | ||
| ```js | ||
| describe('conditional interactions', () => { | ||
| it('handles different input states', () => { | ||
| cy.get('[data-cy="search-input"]').then(($input) => { | ||
| const currentValue = $input.val() | ||
|  | ||
| if (currentValue) { | ||
| // Clear existing value and enter new one | ||
| cy.wrap($input).clear().type('new search term') | ||
| } else { | ||
| // Just enter the new value | ||
| cy.wrap($input).type('new search term') | ||
| } | ||
| }) | ||
| }) | ||
| }) | ||
| ``` | ||
|  | ||
| #### Working with Element Collections | ||
|  | ||
| ```js | ||
| describe('element collections', () => { | ||
| it('processes multiple items', () => { | ||
| cy.get('[data-cy="product-card"]').then(($cards) => { | ||
| // Process each card | ||
| $cards.each((index, card) => { | ||
| cy.wrap(card) | ||
| .should('be.visible') | ||
| .find('[data-cy="product-title"]') | ||
| .should('not.be.empty') | ||
| }) | ||
| }) | ||
| }) | ||
| }) | ||
| ``` | ||
|  | ||
| ### Performance Considerations | ||
|  | ||
| Command chaining is typically more performant because: | ||
|  | ||
| - Cypress optimizes the command queue for chained operations. | ||
| - No additional `cy.wrap()` overhead. | ||
| - Automatic smart retries and element resolution. | ||
| - Better memory management with fewer closures. | ||
|  | ||
| Use `then()` judiciously and only when the additional functionality it provides is necessary for your specific use case. | ||
|  | ||
| ## <Icon name="angle-right" /> Running Tests Intelligently | ||
|  | ||
| As your test suite grows and takes longer to run, you may find yourself hitting | ||
|  | ||
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.