Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cypress wait for transition of the element

describe('Spider application', () => {
  before(() => {
    cy.visit('/');
  });

  it('should center the spider by left border', () => {
      cy.get('.spider').then(($spider) => {
        cy.get('.wall').then(($wall) => {
          const spider = $spider.get(0);
          const wall = $wall.get(0);

          const spiderLeft = spider.getBoundingClientRect().left;
          const spiderLeftAbs = (wall.clientWidth / 2) + (wall.offsetLeft + 10)
          - (spider.width / 2);

          expect(spiderLeft).to.equal(spiderLeftAbs);
        });
      });
    });
  }):

Hello! My test should check the position of the element 'spider'. But without cy.wait(1000) it always fails, as the time of transition is 1s. How to wait for the end of the spider's transition and only after check the actual position?

like image 466
Brian Warner Avatar asked Oct 14 '25 17:10

Brian Warner


1 Answers

You can have Cypress retry the expectation by changing .then() to .should().

I would also change the order you obtain the elements, since .should() retries the preceding command only.

it('should center the spider by left border', () => {
  cy.get('.wall').then(($wall) => {
    cy.get('.spider')
      .should(($spider) => { // repeat .get(spider) until except succeeds, or times out
        ...
        expect(spiderLeft).to.equal(spiderLeftAbs);
      });
  });
});

Also works with triggerable transitions, I tested with a hover transition (using cypress-real-events).

<style type="text/css">
  .target {
    font-size: 14px;
    transition: font-size 1s 1s;
  }
  .target:hover {
    font-size: 36px;
  }
</style>

BTW you may need to use some +/- on the pixels.

like image 171
Richard Matsen Avatar answered Oct 18 '25 05:10

Richard Matsen