cypress

How can I check one element is below another in Cypress with proper retryability?


In testing drag and drop, I want to check the element found by cy.contains(text1) is positioned under the one found by cy.contains(text2).

If I do

cy.contains(text1).as('element1');
return cy.contains(text2).as('element2').should(function () {
  const top1 = this.element1[0].getBoundingClientRect().top;
  const top2 = this.element2[0].getBoundingClientRect().top;
  return top1 > top2;
});

only cy.contains(text2) is retried. I want both cy.contains to be retried since both coordinates are expected to change.

cy.contains(text1).then($el1 => {
  cy.contains(text2).should($el2 => {
    const top1 = this.element1[0].getBoundingClientRect().top;
    const top2 = this.element2[0].getBoundingClientRect().top;
    expect(top1).to.be.greaterThan(top2);
  });
});

similarly doesn't retry cy.contains(text1). Replacing then with another should doesn't work, since cy.contains can't be called inside a should callback function.

Is there a standard Cypress way to achieve that?


Solution

  • You can either install cypress-wait-until for more flexible retries, or use a pure Cypress approach with cy.document().should(...) to ensure retry ability on both elements.enter image description here