Cypress Drag and Drop

Profile picture for user arilio666

Cypress Drag and Drop

Cypress drag and drop is pretty tough. It will take 20 lines of code to drag an element and drop it at the target location.

Take a look at yourself:

it('works (simply)', () => {
    const draggable = Cypress.$('#cdk-drop-list-0 > :nth-child(1)')[0]  // Pick up this
    const droppable = Cypress.$('#cdk-drop-list-1 > :nth-child(4)')[0]  // Drop over this
    const coords = droppable.getBoundingClientRect()
  
    draggable.dispatchEvent(new MouseEvent('mousedown'));
    draggable.dispatchEvent(new MouseEvent('mousemove', {clientX: 10, clientY: 0}));
    draggable.dispatchEvent(new MouseEvent('mousemove', {
    
    clientX: coords.x+10,   
    clientY: coords.y+10  // A few extra pixels to get the ordering right
  }));
  
  draggable.dispatchEvent(new MouseEvent('mouseup'));

  cy.get('#cdk-drop-list-1').should('contain', 'Get to work');
  cy.get('#cdk-drop-list-1 > .cdk-drag').eq(3).should('contain', 'Get to work');
});
  • Yes, this is just a drag and drop operation that takes so much of lines of code to do it.
  • With a simple plugin, we can easily drag and drop an element.
  • First, let us look at how we can install this plugin and set it up to use it.

Cypress Drag and Drop using Plugin

Install Using NPM:

npm install --save-dev @4tw/cypress-drag-drop

cypress drag and drop plugin

Add the following line in command.js:

import '@4tw/cypress-drag-drop'

Add the following line in index.js too:

require('@4tw/cypress-drag-drop')
  • So that's pretty much it.

Let us take a look at how this plugin works.

it('Drag And Drop',()=>{
    cy.visit('https://demo.seleniumeasy.com/drag-and-drop-demo.html')
    cy.get('div#todrag span:nth-of-type(1)').drag('#mydropzone')
})

cypress drag and drop example

  • We get the draggable element selector, and with just a dot, we can see a drag option suggestion, and within the place, the target place to drop the dragged element, that's it.

We can also check the outcome of the event with assertion.

it('Drag And Drop',()=>{
    cy.visit('https://demo.seleniumeasy.com/drag-and-drop-demo.html')

    cy.get('div#todrag span:nth-of-type(1)').drag('#mydropzone').then((success)=>{
        assert.isTrue(success)
    })
})

cypress test drag and drop

  • We can also use move and provide with position, x, and y to move the element around.
cy.visit('http://autopract.com/selenium/drag2/')
cy.get('#winston').move({ deltaX: 100, deltaY: 100 })

Conclusion:

So this plugin will be beneficial and be the best in code minimalism and avoid 20 lines of code with just a dot drag.