Cant get “this.mouse.click()” to work with casperjs

一世执手 提交于 2019-12-01 18:52:22

According to Instant Testing with CasperJS:

casper.click() creates an event and dispatches it to the targeted event, but casper.mouse.click() does not deal with any element but just produces a mouse action at the given position.

That creates the secondary question of why would that make a difference (the w3schools.com HTML is very clean and straightforward, as far as I can see, no invisible layers, or fancy JavaScript interventions on click actions).

And the reason turned out to be very simple. The default viewport size is very small: your button was off-screen, so the mouse could not click it! Here is a quick test script that does work for me:

var casper = require('casper').create();
//var mouse = require("mouse").create(casper);

casper.options.viewportSize = {width: 1024,height: 768};

casper.start('http://www.w3schools.com/');

casper.then(function(){
  this.mouse.click('a.btn'); 
});

casper.then(function(){
   console.log('Location is now: ' + this.getCurrentUrl());
});

casper.run();

I tested with both PhantomJS and SlimerJS. But I only realized the problem when testing with SlimerJS and could see the HTML that was generated. Putting a this.capture("aboutToClick.png"); just before your this.mouse.click('a.btn'); would also have been a good troubleshooting approach.

ASIDE: I've commented out the var mouse line to show you do not need it: a casper object has one internally.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!