Search code examples
cypressdrag

Saving a value and using it later in the command chain


I'm testing a drag scenario, want to get an elements position and use the value in a mousemove. I though that Cypress.env() was a way to save values, but it appears empty in the mousemove parameters. How do I save the initial data?

cy.get('.draggable')
  .then($el => { Cypress.env('start', $el[0].getBoundingClientRect()) })
  .trigger('mousemove', , { pageX: Cypress.env('start').x +20 })

Solution

  • The test commands take their values as the test is run, but the commands run later (asynchronously), so Cypress.env('start') is not yet defined when the mousemove command is queued.

    You can add a .then() to delay queueing that command, and it will read the latest value.

    cy.get('.draggable')
      .then($el => { Cypress.env('start', $el[0].getBoundingClientRect()) })
      .then($el => {
        cy.wrap($el).trigger('mousemove', { pageX: Cypress.env('start').x +20 })
      })