Skip to content

Instantly share code, notes, and snippets.

@drewwiens
Created March 1, 2021 20:45
Show Gist options
  • Save drewwiens/4c0508c24e63dfb3a227e7a0db908a04 to your computer and use it in GitHub Desktop.
Save drewwiens/4c0508c24e63dfb3a227e7a0db908a04 to your computer and use it in GitHub Desktop.
Testing Angular Material drag and drop with Cypress
Cypress.Commands.add(
'dragDrop',
{ prevSubject: false },
(selector: string, originIdx: number, destIdx: number) => {
// Based on https://stackoverflow.com/a/55436989
const elements = Cypress.$(selector);
[originIdx, destIdx].forEach((idx) => {
if (originIdx < 0 || originIdx >= elements.length) {
throw Error(
`Cannot index element ${idx} of ${elements.length} draggable elements.`,
);
}
});
const origin = elements[originIdx].getBoundingClientRect();
const destination = elements[destIdx].getBoundingClientRect();
// All three (client, screen, and page) must be defined:
const options = (rect: DOMRect, offset = 0) => ({
button: 0,
clientX: rect.x + offset,
clientY: rect.y + offset,
screenX: rect.x + offset,
screenY: rect.y + offset,
pageX: rect.x + offset,
pageY: rect.y + offset,
});
cy.wrap(elements[originIdx])
.trigger('mousedown', options(origin))
.trigger('mousemove', options(origin, 10))
.trigger('mousemove', { ...options(destination, 10), force: true })
.trigger('mouseup', { ...options(destination, 10), force: true });
},
);
// Add typing to global namespace:
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace Cypress {
interface Chainable<Subject> {
/**
* Cypress command to drag and drop HTML elements.
* @param selector JQuery selector that selects all the draggable items.
* @param originIdx Index of the item to drag.
* @param destIdx Index of the other item to drag-drop onto.
*/
dragDrop(
selector: string,
originIdx: number,
destIdx: number,
): Chainable<Subject>;
}
}
}
export {}; // Indicate to compiler that this file is a module
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment