I am writing some integration tests, and I want to simulate user interactions in the most literal possible way. My approach was to create an animated mouse pointer, which tweens mouse movements. The mouse movements are simulated using the following:
eventTarget.dispatchEvent(new MouseEvent("mousemove", {
clientX: x,
clientY: y,
bubbles: true,
}));
As far as my trying out goes, these artificial mouse events do not cause consequent mouseenter and mouseleave event triggers. For the purpose of my tests, I'd like these events to take place as if it were a real mouse moving around.
- How could I cause the consequential events of an organic interaction take place in the context of an automated test in a browser?
- Am I wrong about my conclusion that consequential
mouseenterandmouseleaveevents don't take place as consequence of dispatchingmousemoveon the coordinates where anHTMLElementis located?
here my concept testing code:
const innerEl = document.querySelector("#inner")
const mouseEl = document.querySelector("#mouse")
const mouse = {
x:0, y:0
}
// this one will obviously be triggered by dispatching mousemove
document.addEventListener("mousemove",(ev)=>{
mouse.x = ev.clientX
mouse.y = ev.clientY
mouseEl.style.left = mouse.x + "px";
mouseEl.style.top = mouse.y + "px";
})
// will these get triggered as consequence?
innerEl.addEventListener("mouseenter",(ev)=>{
innerEl.style.backgroundColor="red"
})
innerEl.addEventListener("mouseleave",(ev)=>{
innerEl.style.backgroundColor = ""
})
const innerLocation = innerEl.getBoundingClientRect()
const frame = (t) => {
const x = Math.cos(t / 1000 ) * 10 + innerLocation.right;
const y = Math.sin(t / 1000 ) * 10 + innerLocation.bottom;
document.dispatchEvent(new MouseEvent("mousemove", {
clientX: x,
clientY: y,
bubbles: true,
}));
requestAnimationFrame(frame)
}
requestAnimationFrame(frame)
(jsfiddle: https://jsfiddle.net/wxz139bo/2/)
it would appear the browser does not auto generate events for you and this is probably a good thing allowing the programmer to have fine grained control and generate exactly what they want
if you want to handle generating mouse events you'll have to go the whole 9 yards with it
there is a very definate order to which mouse events and in what order, as with absolutely everything webpage/html related, according to the spec Mouse Event Order