用水豚模拟鼠标移动

时间:2019-03-04 11:10:38

标签: capybara

我想在运行Capybara测试时演示鼠标在屏幕上的移动。除了要遍历数据点等之外,我还要求使用户能够看到鼠标移动。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:0)

我所知的任何Capybara驱动程序均不直接支持此功能,但是您可以使用Visualize / Show mouse cursor position in selenium 2 tests (for example PHPUnit Webdriver)中所示的JS伪造鼠标指针

基本上,它可以简化为创建图像,然后在每次发生mousemove事件时移动其位置

// Create mouse following image.
var seleniumFollowerImg = document.createElement("img");

// Set image properties.
seleniumFollowerImg.setAttribute('src', 'data:image/png;base64,'
    + 'iVBORw0KGgoAAAANSUhEUgAAABQAAAAeCAQAAACGG/bgAAAAAmJLR0QA/4ePzL8AAAAJcEhZcwAA'
    + 'HsYAAB7GAZEt8iwAAAAHdElNRQfgAwgMIwdxU/i7AAABZklEQVQ4y43TsU4UURSH8W+XmYwkS2I0'
    + '9CRKpKGhsvIJjG9giQmliHFZlkUIGnEF7KTiCagpsYHWhoTQaiUUxLixYZb5KAAZZhbunu7O/PKf'
    + 'e+fcA+/pqwb4DuximEqXhT4iI8dMpBWEsWsuGYdpZFttiLSSgTvhZ1W/SvfO1CvYdV1kPghV68a3'
    + '0zzUWZH5pBqEui7dnqlFmLoq0gxC1XfGZdoLal2kea8ahLoqKXNAJQBT2yJzwUTVt0bS6ANqy1ga'
    + 'VCEq/oVTtjji4hQVhhnlYBH4WIJV9vlkXLm+10R8oJb79Jl1j9UdazJRGpkrmNkSF9SOz2T71s7M'
    + 'SIfD2lmmfjGSRz3hK8l4w1P+bah/HJLN0sys2JSMZQB+jKo6KSc8vLlLn5ikzF4268Wg2+pPOWW6'
    + 'ONcpr3PrXy9VfS473M/D7H+TLmrqsXtOGctvxvMv2oVNP+Av0uHbzbxyJaywyUjx8TlnPY2YxqkD'
    + 'dAAAAABJRU5ErkJggg==');
seleniumFollowerImg.setAttribute('id', 'selenium_mouse_follower');
seleniumFollowerImg.setAttribute('style', 'position: absolute; z-index: 99999999999; pointer-events: none;');

// Add mouse follower to the web page.
document.body.appendChild(seleniumFollowerImg);
document.addEventListener('mousemove', function(e) {
  const mousePointer = document.getElementById('selenium_mouse_follower');
  mousePointer.style.left = e.pageX + 'px';
  mousePointer.style.top = e.pageY + 'px';
});

然后,您需要确保在每次页面更改(访问,单击导航等)后执行JS。您可以通过多种方式进行操作,最简单的方法是在测试模式下有条件地将代码添加到您的应用中,或者在希望显示下一步操作的鼠标位置时使用调用page.execute_js的帮助程序方法手动进行调用