cypress-documentation icon indicating copy to clipboard operation
cypress-documentation copied to clipboard

Best practice - then() usage vs chained commands

Open rsi21 opened this issue 5 months ago • 0 comments

Description

Hi,

I wanted to clarify some best practices around then() function and 'classical' chaining.
What is the best practice for example when interacting with an input where we want to:

  • focus
  • remove current text content
  • write a new value
  • and blur

I ask that because, it is a common practice and i read several ways to do it but some of them seems unstable:

  1. First option: The most classic is to make the commands succesively as some of them cannot be chained (type(), focus(), clear()...) So it will be:
cy.get('form #stripe-payment-element').focus(); 
cy.get('form #stripe-payment-element').clear();  
cy.get('form #stripe-payment-element').type('new value');  
cy.get('form #stripe-payment-element').blur();  
  1. Second option: use the then() function to wrap all actions. So it will be:
cy.get('form #stripe-payment-element').then(($input) => {
        cy.wrap($input).focus();
        cy.wrap($input).clear();
        cy.wrap($input).type(value);
        cy.wrap($input).blur();
  });

This last case seems to be, as what i read, the most appropriate as:

  • it reduces risks of "detached DOM errors"
  • the input if found once and not re-searched 3 times

Is it the best approach ? But also the most performant too ?

Documentation is really well done, but with so many posibilities, sometimes it is hard to choose the best approach :)

Hope my question is clear!

rsi21 avatar May 19 '25 16:05 rsi21