Brian Warner
Brian Warner

Reputation: 43

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?

Upvotes: 4

Views: 21712

Answers (2)

Richard Matsen
Richard Matsen

Reputation: 23483

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.

Upvotes: 5

MetaWhirledPeas
MetaWhirledPeas

Reputation: 486

Is it safe to click on the element? If so, interacting with it first might trigger Cypress to wait for the animation.

cy.get('.spider').click().then(($spider) => {

My reasoning: https://docs.cypress.io/guides/core-concepts/interacting-with-elements.html#Animations

Cypress will automatically determine if an element is animating and wait until it stops.

Upvotes: 3

Related Questions