how to automate dragndrop using cypress plugin

50 Views Asked by At

not able to drag the first task in my list to 3 task

cy.get('div[data-columns="columns"]')
      .find('div[data-columnContainer="columnContainer"]')
      .each(($column) => {
        if ($column.text().includes("Hamza Malik")) {
          cy.get('div[data-taskDraggable="taskDraggable"]:nth-child(1)').drag('div[data-taskDraggable="taskDraggable"]:nth-child(3)', { force: true });
        }
      });
1

There are 1 best solutions below

0
Grace Rizzo On

There is the trigger() command for simple situations, the example is here

cy.get('div[data-columns="columns"]')
  .contains('div[data-columnContainer="columnContainer"]', 'Hamza Malik')
  .find('[data-cy=draggable]')
  .trigger('mousedown', { which: 1, pageX: 600, pageY: 100 })
  .trigger('mousemove', { which: 1, pageX: 600, pageY: 600 })
  .trigger('mouseup')

But this means some calculation of x-y points which is not ideal, and can break if the page layout changes.

Since you already use cypress-drag-drop, I suggest the selectors need changing. The code that finds your name is not affecting the drag operation.

I think using .within() gives you better results:

cy.get('div[data-columns="columns"]')
  .contains('div[data-columnContainer="columnContainer"]', 'Hamza Malik')
  .within(() => {

    // Now queries operate within the specified container column

    cy.get('div[data-taskDraggable="taskDraggable"])
      .then(draggables => {
        cy.wrap(draggables.eq(0))   // drag first over third
          .drag(draggables.eq(2))
      })
  })