Skip to content

Instantly share code, notes, and snippets.

@david-j-davis
Last active March 29, 2017 11:05
Show Gist options
  • Save david-j-davis/52767756ecda4cb0e03b673ef25e802b to your computer and use it in GitHub Desktop.
Save david-j-davis/52767756ecda4cb0e03b673ef25e802b to your computer and use it in GitHub Desktop.
Casper.js headless test tool screenshot example

Using Casper.js

What is Casper?

It's a headless testing tool. Description taken from: https://www.npmjs.com/package/casperjs CasperJS is a navigation scripting & testing utility for PhantomJS and SlimerJS (still experimental). It eases the process of defining a full navigation scenario and provides useful high-level functions, methods & syntactic sugar for doing common tasks such as:

  1. defining & ordering navigation steps
  2. filling forms
  3. clicking links
  4. capturing screenshots of a page (or an area)
  5. making assertions on remote DOM
  6. logging & events
  7. downloading resources, even binary ones
  8. catching errors and react accordingly
  9. writing functional test suites, exporting results as JUnit XML (xUnit)
  • first install phantomjs and casperjs globally with install.sh so you can use it in the terminal. Alternatively you can brew install both of them.
  • Next create a tests folder in your project directory to house your tests
  • Create a js file like you see below or something similar to accomplish what you are looking for
  • Start using it. In this specific gist example, we take a screenshot of a twitter account the user enters like: Usage: $ casperjs tests/screenshot.js twitter-account filename.[jpg|png|pdf]
  • Alternately you can create your own npm scripts for various preconfigured tests and do things like fill out a form, then take a screenshot. Click a button, and then take a screenshot, take a screenshot at mobile, tablet, and desktop size, etc.
npm install -g phantomjs
npm install -g casperjs
/*eslint strict:0*/
/*global CasperError, console, phantom, require*/
/**
* This script will capture a screenshot of a twitter account page
* Usage: $ casperjs tests/screenshot.js <twitter-account> <filename.[jpg|png|pdf]>
*/
var casper = require("casper").create({
viewportSize: {
width: 1024,
height: 768
}
});
/* get arguments entered by user in Terminal */
var twitterAccount = casper.cli.get(0);
var filename = casper.cli.get(1);
if (!twitterAccount || !filename || !/\.(png|jpg|pdf)$/i.test(filename)) {
casper
.echo("Usage: $ casperjs screenshot.js <twitter-account> <filename.[jpg|png|pdf]>")
.exit(1)
;
}
casper.start("https://twitter.com/" + twitterAccount, function() {
this.waitForSelector(".stream-container", (function() {
this.captureSelector(filename, "html");
this.echo("Saved screenshot of " + (this.getCurrentUrl()) + " to " + filename);
}), (function() {
this.die("Timeout reached. Fail whale?");
this.exit();
}), 12000);
});
casper.run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment