Ognjen Regoje bio photo

Ognjen Regoje
But you can call me Oggy


I make things that run on the web (mostly).
More ABOUT me and my PROJECTS.

me@ognjen.io LinkedIn

Tracking the cursor in Selenium driven Chrome

#minitest #rails #selenium #testing

From the links in the sources, the following code snippet can be used to track the cursor:

<style>
  .dot {
    background: red;
    position: absolute;
    width: 2px;
    height: 2px;
    z-index: 10000;
  }
</style>
(function () {
  "use strict";

  document.onmousemove = handleMouseMove;
  function handleMouseMove(event) {
    var dot, eventDoc, doc, body, pageX, pageY;

    event = event || window.event; // IE-ism

    // If pageX/Y aren't available and clientX/Y
    // are, calculate pageX/Y - logic taken from jQuery
    // Calculate pageX/Y if missing and clientX/Y available
    if (event.pageX == null && event.clientX != null) {
      eventDoc = (event.target && event.target.ownerDocument) || document;
      doc = eventDoc.documentElement;
      body = eventDoc.body;

      event.pageX =
        event.clientX +
        ((doc && doc.scrollLeft) || (body && body.scrollLeft) || 0) -
        ((doc && doc.clientLeft) || (body && body.clientLeft) || 0);
      event.pageY =
        event.clientY +
        ((doc && doc.scrollTop) || (body && body.scrollTop) || 0) -
        ((doc && doc.clientTop) || (body && body.clientTop) || 0);
    }

    // Add a dot to follow the cursor
    dot = document.createElement("div");
    dot.className = "dot";
    dot.style.left = event.pageX + "px";
    dot.style.top = event.pageY + "px";
    document.body.appendChild(dot);
  }
})();

You can then wrap that into a helper that you can call in your test. You can just page.execute_script(helper_js) and you can inject the CSS similarly.

Then binding.pry after that’s done and move the cursor around to get the correct offsets.

Note that if you add this javascript snippet hover will no longer trigger on your elements because a new dot element will always be under the cursor.