Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cypress - Drag & drop - Angular CDK

Having a simple implementation of the Angular CDK drag & drop, with cypress. Having latest versions of all packages, all the questions & solutions around wont work.

Basically, the drag & drop wont eve fire.

Tried with

  • https://www.npmjs.com/package/@4tw/cypress-drag-drop
  • https://docs.cypress.io/api/commands/trigger
  • Even with the answers to this "solved" question on stackoverflow How to implement drag and drop in cypress test?

But nothing would work.

like image 765
mmonteirocl Avatar asked Oct 18 '25 12:10

mmonteirocl


2 Answers

When we found the problem, we manage to find the solution.

In a nutshell, the problem is that angular material - cdk, in latest versions, they are blocking the "drag and drop" from screen readers, for accessibility purposes. Which is ok, the problem is that the library / solutions posted, they were considered as "screen readers" as the "buttons" was 0 in the event.

In some of the cases, just by providing the "buttons = 1" would be enough, but that wasnt our case.

Because our case was a complex Drag & Drop where, you could only drag from the "handle" and you would be limited in the area of the list (so only move in Y axis) these solutions would not work.

The only & best solution that worked for US so far has been the following one: Using the cypress plugin cypress-real-events

const selectorForDraggingElementOrHanlde = 'whatever css selector u need'
const selectorWhereToDropTheElement = 'whatever other css selector u need'

cy.get(selectorForDraggingElementOrHanlde)
        .realMouseDown({ button: 'left', position: 'center' })
        .realMouseMove(0, 10, { position: 'center' });
cy.wait(200) // In our case, we wait 200ms cause we have animations which we are sure that take this amount of time
cy.get(selectorWhereToDropTheElement ).realMouseMove(0, 0, { position: 'center' }).realMouseUp();
like image 170
mmonteirocl Avatar answered Oct 21 '25 01:10

mmonteirocl


The solution provided by mmonteirocl above worked perfectly for me as well. I implemented it as a custom command in our commands.js:

Cypress.Commands.add('dragAndDrop', (subjectSelector, targetSelector) => {
    cy.get(subjectSelector)
        .realMouseDown({ button: 'left', position: 'center' })
        .realMouseMove(0, 10, { position: 'center' });
    cy.get(targetSelector).realMouseMove(0, 0, { position: 'center' }).realMouseUp();
});

Then called it the test like:

cy.dragAndDrop(subjectSelector, targetSelector);
like image 35
SSH Avatar answered Oct 21 '25 02:10

SSH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!