Cypress mousemove event inconsistency
Cypress is a great testing tool, but as always testing comes with some behaviors that you cannot predict. I have stumbled upon one recently and wanted to share.
If your feature uses mouse events, to test their behavior properly, do not use methods provided by Cypress like trigger. Instead find the native element and dispatch event natively.
For example, if I have logic on mousemove event, Cypress documentation suggests doing something like this.
cy.get('...').trigger('mousemove', x, y);Visually in Cypress runner it looks fine, but under the hood mouse is immediately moved to the position with an empty event. So, if my logic uses fields movementX and movementY for let's say positioning, we have a problem here - fields that are used from native event are undefined, so it would not move elements to proper places. This behavior is consistent with other Cypress commands like click.
So to fix that, we can do something like this.
cy.get('...').then((element) => {
const mouseEvent = new MouseEvent('mousemove', {
movementX: x,
movementY: y,
});
element.get(0).dispatchEvent(mouseEvent);
});Bonus
if your code checks which button is pressed on mouse, you should explicitly mention the button when dispatching events like mousedown and mouseup via trigger, else they are also undefined. Or just use proper functions like click.