4

Im trying to understand casperjs but struggling with this. Can someone pleas tell me why this works (it navigates to http://www.w3schools.com/html/default.asp):

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

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

casper.then(function(){

  this.click('a.btn'); 
});

casper.then(function(){

   console.log('Location is now: ' + this.getCurrentUrl());
});

casper.run();

But if i replace

this.click('a.btn'); 

with

this.mouse.click('a.btn');

Then it stays on the same page. I thought these where the same.

SteinarV
  • 57
  • 1
  • 8

1 Answers1

4

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.

Darren Cook
  • 27,837
  • 13
  • 117
  • 217