简体   繁体   中英

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

But nothing would work.

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();

This worked perfectly for me as well. I implemented it as a custom command in our commands.js:

Cypress.Commands.add('dragAndDrop', (subjectSelector, targetSelector) => {
    const selectorForDraggingElementOrHanlde = subjectSelector
    const selectorWhereToDropTheElement = targetSelector

    cy.get(selectorForDraggingElementOrHanlde)
        .realMouseDown({ button: 'left', position: 'center' })
        .realMouseMove(0, 10, { position: 'center' });
    cy.get(selectorWhereToDropTheElement).realMouseMove(0, 0, { position: 'center' }).realMouseUp();
});

Then called it the test like:

cy.dragAndDrop(subjectSelector, targetSelector);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM