This page details the APIs of the following CasperJS classes & modules, as well as their usage:
Api documentation
The Casper class
Casper source code is quite heavily documented using jsdoc
, but below
you'll find the whole API documentation with sample code.
The Casper class
The most easy way to instantiate a casper instance is to use the
module's create()
method:
var casper = require('casper').create();
But you can also retrieve the main Function and instantiate it by yourself:
var casper = new require('casper').Casper();
Hint Also, check out how to extend Casper with your own methods.
Casper([Object options])
Both the Casper
constructor and the create()
function accept a
single options
argument which is a standard javascript object:
var casper = require('casper').create({
verbose: true,
logLevel: "debug"
});
Casper options
All the available options are detailed below:
Name | Type | Default | Description |
---|---|---|---|
clientScripts |
Array |
[] |
A collection of script filepaths to include to every page loaded |
exitOnError |
Boolean |
true |
Sets if CasperJS must exit when an uncaught error has been thrown by the script. |
httpStatusHandlers |
Object |
{} |
A javascript Object containing functions to call when a requested resource has a given HTTP status code. A dedicated sample is provided as an example. |
logLevel |
String |
"error" |
Logging level (see the logging section for more information) |
onAlert |
Function |
null |
A function to be called when a javascript alert()
is triggered
|
onDie |
Function |
null |
A function to be called when Casper#die()
is called
|
onError |
Function |
null |
A function to be called when an "error"
level event occurs
|
onLoadError |
Function |
null |
A function to be called when a requested resource cannot be loaded |
onPageInitialized |
Function |
null |
A function to be called after WebPage
instance has been initialized |
onResourceReceived |
Function |
null |
Proxy method for PhantomJS' WebPage#onResourceReceived()
callback, but the current Casper instance is passed as
first argument.
|
onResourceRequested |
Function |
null |
Proxy method for PhantomJS' WebPage#onResourceRequested()
callback, but the current Casper instance is passed as
first argument.
|
onStepComplete |
Function |
null |
A function to be executed when a step function execution is finished. |
onStepTimeout |
Function |
Function |
A function to be executed when a step function
execution time exceeds the value of the By default, on timeout the script will exit displaying an error, except in test environment where it will just add a failure to the suite results. |
onTimeout |
Function |
Function |
A function to be executed when script execution time
exceeds the value of the By default, on timeout the script will exit displaying an error, except in test environment where it will just add a failure to the suite results. |
onWaitTimeout |
Function |
Function |
A function to be executed when a By default, on timeout the script will exit displaying an error, except in test environment where it will just add a failure to the suite results. |
page |
WebPage |
null |
An existing WebPage instance |
pageSettings |
Object |
{} |
PhantomJS's
|
remoteScripts |
Array |
[] |
Added in 1.0 A collection of remote script urls to include to every page loaded |
safeLogs |
Boolean |
true |
Added in 1.0
When this option is set to true — which is the
default, any password information entered in
<input type="password"> will be obfuscated in log
messages. Set safeLogs to false to disclose passwords in
plain text (not recommended).
|
stepTimeout |
Number |
null |
Max step timeout in milliseconds; when set, every
defined step function will have to execute before this
timeout value has been reached. You can define the onStepTimeout()
callback to catch such a case. By default, the script will
die() with an error message. |
timeout |
Number |
null |
Max timeout in milliseconds |
verbose |
Boolean |
false |
Realtime output of log messages |
viewportSize |
Object |
null |
Viewport size, eg. {width: 800, height: 600} |
waitTimeout |
Number |
5000 |
Default wait timeout, for wait family functions. |
Example:
var casper = require('casper').create({
clientScripts: [
'includes/jquery.js', // These two scripts will be injected in remote
'includes/underscore.js' // DOM on every request
],
logLevel: "info", // Only "info" level messages will be logged
onError: function(self, m) { // Any "error" level message will be written
console.log('FATAL:' + m); // on the console output and PhantomJS will
self.exit(); // terminate
},
pageSettings: {
loadImages: false, // The WebPage instance used by Casper will
loadPlugins: false // use these settings
}
});
But no worry, usually you'll just need to instantiate Casper using
require('casper').create()
.
Casper#back()
Moves back a step in browser's history.
casper.start('http://foo.bar/1')
casper.thenOpen('http://foo.bar/2');
casper.thenOpen('http://foo.bar/3');
casper.back();
casper.run(function() {
console.log(this.getCurrentUrl()); // 'http://foo.bar/2'
});
Also have a look at Casper.forward()
.
Casper#base64encode(String url [, String method, Object data])
Encodes a resource using the base64 algorithm synchronously using client-side XMLHttpRequest.
Note We cannot use window.btoa()
because it fails miserably in the version of WebKit shipping with PhantomJS.
Example: retrieving google logo image encoded in base64:
var base64logo = null;
casper.start('http://www.google.fr/', function() {
base64logo = this.base64encode('http://www.google.fr/images/srpr/logo3w.png');
});
casper.run(function() {
this.echo(base64logo).exit();
});
You can also perform an HTTP POST request to retrieve the contents to encode:
var base46contents = null;
casper.start('http://domain.tld/download.html', function() {
base46contents = this.base64encode('http://domain.tld/', 'POST', {
param1: 'foo',
param2: 'bar'
});
});
casper.run(function() {
this.echo(base46contents).exit();
});
Casper#click(String selector)
Performs a click on the element matching the provided selector expression. The method tries two strategies sequentially:
- trying to trigger a MouseEvent in Javascript
- using native QtWebKit event if the previous attempt failed
Example:
casper.start('http://google.fr/');
casper.thenEvaluate(function(term) {
document.querySelector('input[name="q"]').setAttribute('value', term);
document.querySelector('form[name="f"]').submit();
}, { term: 'CasperJS' });
casper.then(function() {
// Click on 1st result link
this.click('h3.r a');
});
casper.then(function() {
console.log('clicked ok, new location is ' + this.getCurrentUrl());
});
casper.run();
Casper#clickLabel(String label[, String tag])
Added in 0.6.10
Clicks on the first DOM element found containing label
text.
Optionaly ensures that the element node name is tag
.
// <a href="...">My link is beautiful</a>
casper.then(function() {
this.clickLabel('My link is beautiful', 'a');
});
// <button type="submit">But my button is sexier</button>
casper.then(function() {
this.clickLabel('But my button is sexier', 'button');
});
Casper#capture(String targetFilepath, Object clipRect)
Proxy method for PhantomJS' WebPage#render
. Adds a clipRect parameter
for automatically setting page clipRect setting values and sets it back
once done.
Example:
casper.start('http://www.google.fr/', function() {
this.capture('google.png', {
top: 100,
left: 100,
width: 500,
height: 400
});
});
casper.run();
Casper#captureBase64(String format[, Mixed area])
Added in 0.6.5 PhantomJS >= 1.6 Computes the Base64 representation of a binary image capture of the current page, or an area within the page, in a given format.
Supported image formats are bmp
, jpg
, jpeg
, png
, ppm
, tiff
,
xbm
and xpm
.
The area
argument can be either of the following types:
String
: area is a CSS3 selector string, eg.div#plop form[name="form"] input[type="submit"]
clipRect
: area is a clipRect object, eg.{"top":0,"left":0,"width":320,"height":200}
Object
: area is a selector object, eg. an XPath selectorExample:*
casper.start('http://google.com', function() {
// selector capture
console.log(this.captureBase64('png', '#lga'));
// clipRect capture
console.log(this.captureBase64('png', {
top: 0,
left: 0,
width: 320,
height: 200
}));
// whole page capture
console.log(this.captureBase64('png'));
});
casper.run();
Casper#captureSelector(String targetFile, String selector)
Captures the page area containing the provided selector.
Example:
casper.start('http://www.weather.com/', function() {
this.captureSelector('weather.png', '#wx-main');
});
casper.run();
Casper#clear()
Added in 0.6.5 Clears the current page execution environment context. Useful to avoid having previously loaded DOM contents being still active.
Think of it as a way to stop javascript execution within the remote DOM environment.
Example:
casper.start('http://www.google.fr/', function() {
this.clear(); // javascript execution in this page has been stopped
});
casper.then(function() {
// ...
});
casper.run();
Casper#debugHTML([String selector, Boolean outer])
Outputs the results of getHTML()
directly to the console. It takes
the same arguments as getHTML()
.
Casper#debugPage()
Logs the textual contents of the current page directly to the standard output, for debugging purpose.
Example:
casper.start('http://www.google.fr/', function() {
this.debugPage();
});
casper.run();
Casper#die(String message[, int status])
Exits phantom with a logged error message and an optional exit status code.
Example:
casper.start('http://www.google.fr/', function() {
this.die("Fail.", 1);
});
casper.run();
Casper#download(String url, String target[, String method, Object data])
Saves a remote resource onto the filesystem. You can optionally set the HTTP
method using the method
argument, and pass request arguments through the
data
object (see base64encode).
casper.start('http://www.google.fr/', function() {
var url = 'http://www.google.fr/intl/fr/about/corporate/company/';
this.download(url, 'google_company.html');
});
casper.run(function() {
this.echo('Done.').exit();
});
Casper#each(Array array, Function fn)
Iterates over provided array items and execute a callback.
Example:
var links = [
'http://google.com/',
'http://yahoo.com/',
'http://bing.com/'
];
casper.start().each(links, function(self, link) {
self.thenOpen(link, function() {
this.echo(this.getTitle());
});
});
casper.run();
Hint Have a look at the googlematch.js sample script for a concrete use case.
Casper#echo(String message[, String style])
Prints something to stdout, optionally with some fancy color (see the
Colorizer
section of this document for more
information).
Example:
casper.start('http://www.google.fr/', function() {
this.echo('Page title is: ' + this.evaluate(function() {
return document.title;
}), 'INFO'); // Will be printed in green on the console
});
casper.run();
Casper#evaluate(Function fn[, Object replacements])
Evaluates an expression in the remote page context, a bit like what PhantomJS'
WebPage#evaluate
does, but can also handle passed arguments if you
define their context:
Example:
casper.evaluate(function(username, password) {
document.querySelector('#username').value = username;
document.querySelector('#password').value = password;
document.querySelector('#submit').click();
}, {
username: 'sheldon.cooper',
password: 'b4z1ng4'
});
Note For filling and submitting forms, rather use the
Casper#fill()
method.
Note The concept behind this method is
probably the most difficult to understand when discovering CasperJS.
As a reminder, think of the evaluate()
method as a gate between the CasperJS
environment and the one of the page you have opened; everytime you pass a closure to
evaluate()
, you're entering the page and execute code as if you were using the
browser console.
Here's a quickly drafted diagram trying to basically explain the separation of concerns:
Casper#evaluateOrDie(Function fn[, String message])
Evaluates an expression within the current page DOM and die()
if it
returns anything but true
.
Example:
casper.start('http://foo.bar/home', function() {
this.evaluateOrDie(function() {
return /logged in/.match(document.title);
}, 'not authenticated');
});
casper.run();
Casper#exit([int status])
Exits PhantomJS with an optional exit status code.
Casper#exists(String selector)
Checks if any element within remote DOM matches the provided selector.
casper.start('http://foo.bar/home', function() {
if (this.exists('#my_super_id')) {
this.echo('found #my_super_id', 'INFO');
} else {
this.echo('#my_super_id not found', 'ERROR');
}
});
casper.run();
Casper#fetchText(String selector)
Retrieves text contents matching a given selector expression. If you provide one matching more than one element, their textual contents will be concatenated.
casper.start('http://google.com/search?q=foo', function() {
this.echo(this.fetchText('h3'));
}).run();
Casper#forward()
Moves a step forward in browser's history.
casper.start('http://foo.bar/1')
casper.thenOpen('http://foo.bar/2');
casper.thenOpen('http://foo.bar/3');
casper.back(); // http://foo.bar/2
casper.back(); // http://foo.bar/1
casper.forward(); // http://foo.bar/2
casper.run();
Also have a look at Casper.back()
.
Casper#log(String message[, String level, String space])
Logs a message with an optional level in an optional space. Available
levels are debug
, info
, warning
and error
. A space is a kind of
namespace you can set for filtering your logs. By default, Casper logs
messages in two distinct spaces: phantom
and remote
, to distinguish
what happens in the PhantomJS environment from the remote one.
Example:
casper.start('http://www.google.fr/', function() {
this.log("I'm logging an error", "error");
});
casper.run();
Casper#fill(String selector, Object values[, Boolean submit])
Fills the fields of a form with given values and optionally submits it.
Example with this sample html form:
<form action="/contact" id="contact-form" enctype="multipart/form-data">
<input type="text" name="subject"/>
<textearea name="content"></textearea>
<input type="radio" name="civility" value="Mr"/> Mr
<input type="radio" name="civility" value="Mrs"/> Mrs
<input type="text" name="name"/>
<input type="email" name="email"/>
<input type="file" name="attachment"/>
<input type="checkbox" name="cc"/> Receive a copy
<input type="submit"/>
</form>
A script to fill and submit this form:
casper.start('http://some.tld/contact.form', function() {
this.fill('form#contact-form', {
'subject': 'I am watching you',
'content': 'So be careful.',
'civility': 'Mr',
'name': 'Chuck Norris',
'email': 'chuck@norris.com',
'cc': true,
'attachment': '/Users/chuck/roundhousekick.doc'
}, true);
});
casper.then(function() {
this.evaluateOrDie(function() {
return /message sent/.test(document.body.innerText);
}, 'sending message failed');
});
casper.run(function() {
this.echo('message sent').exit();
});
Please Don't use CasperJS nor PhantomJS to send spam, or I'll be calling the Chuck. More seriously, please just don't.
Warning The fill()
method currently
can't fill file fields using XPath selectors; PhantomJS natively only allows
the use of CSS3 selectors in
its
uploadFile method, hence this limitation.
Casper#getCurrentUrl()
Retrieves current page URL. Note the url will be url-decoded.
Example:
casper.start('http://www.google.fr/', function() {
this.echo(this.getCurrentUrl()); // "http://www.google.fr/"
});
casper.run();
Casper#getElementAttribute(String selector, String attribute)
Added in 1.0 Retrieves the value of an attribute on the first element matching the provided selector.
Example:
var casper = require('casper').create();
casper.start('http://www.google.fr/', function() {
require('utils').dump(this.getElementAttribute('div[title="Google"]', 'title')); // "Google"
});
casper.run();
Casper#getElementBounds(String selector)
Retrieves boundaries for a DOM element matching the provided selector.
It returns an Object with four keys: top
, left
, width
and height
, or
null
if the selector doesn't exist.
Example:
var casper = require('casper').create();
casper.start('http://www.google.fr/', function() {
require('utils').dump(this.getElementBounds('div[title="Google"]'));
});
casper.run();
This will output something like:
{
"height": 95,
"left": 352,
"top": 16,
"width": 275
}
Casper#getElementsBounds(String selector)
Added in 1.0.0 Retrieves a list of boundaries for all DOM elements matching the provided selector.
It returns an array of objects with four keys: top
, left
, width
and
height
(see casper.getElementBounds()).
Casper#getElementInfo(String selector)
Retrieves information about the first element matching the provided selector.
Added in 1.0
casper.start('http://google.com/', function() {
require('utils').dump(this.getElementInfo('#hplogo'));
});
Gives something like:
{
"nodeName": "div",
"attributes": {
"dir": "ltr",
"title": "Google",
"align": "left",
"id": "hplogo",
"onload": "window.lol&&lol()",
"style": "background:url(images/srpr/logo3w.png) no-repeat;background-size:275px 95px;height:95px;width:275px"
},
"tag": "<div dir=\"ltr\" title=\"Google\" align=\"left\" id=\"hplogo\" onload=\"window.lol&&lol()\" style=\"background:url(images/srpr/logo3w.png) no-repeat;background-size:275px 95px;height:95px;width:275px\"><div nowrap=\"nowrap\" style=\"color:#777;font-size:16px;font-weight:bold;position:relative;left:214px;top:70px\">France</div></div>",
"html": "<div nowrap=\"nowrap\" style=\"color:#777;font-size:16px;font-weight:bold;position:relative;left:214px;top:70px\">France</div>",
"text": "France\n",
"x": 582.5,
"y": 192,
"width": 275,
"height": 95,
"visible": true
}
Casper#getFormValues(String selector)
Added in 1.0 Retrieves a given form all of its field values.
Example:
casper.start('http://www.google.fr/', function() {
this.fill('form', {q: 'plop'}, false);
this.echo(this.getFormValues('form').q); // 'plop'
});
casper.run();
Casper#getGlobal(String name)
Retrieves a global variable value within the remote DOM environment by
its name. Basically, getGlobal('foo')
will retrieve the value of window.foo
from the page.
Example:
casper.start('http://www.google.fr/', function() {
this.echo(this.getGlobal('innerWidth')); // 1024
});
casper.run();
Casper#getHTML([String selector, Boolean outer])
Added in 1.0 Retrieves HTML code from the current page. By default, it outputs the whole page HTML contents:
casper.start('http://www.google.fr/', function() {
this.echo(this.getHTML());
});
casper.run();
getHTML()
can also dump HTML contents matching a given CSS3/XPath selector:
<html>
<body>
<h1 id="foobar">Plop</h1>
</body>
</html>
casper.start('http://www.site.tld/', function() {
this.echo(this.getHTML('h1#foobar')); // => 'Plop'
});
The outer
argument allows to retrieve the outer HTML contents of the matching element:
casper.start('http://www.site.tld/', function() {
this.echo(this.getHTML('h1#foobar', true)); // => '<h1 id="foobar">Plop</h1>'
});
Casper#getPageContent()
Added in 1.0.0 Retrieves current page contents, dealing with exotic other content types than HTML.
Example:
var casper = require('casper').create();
casper.start().then(function() {
this.open('http://search.twitter.com/search.json?q=casperjs', {
method: 'get',
headers: {
'Accept': 'application/json'
}
});
});
casper.run(function() {
require('utils').dump(JSON.parse(this.getPageContent()));
this.exit();
});
Casper#getTitle()
Retrieves current page title.
Example:
casper.start('http://www.google.fr/', function() {
this.echo(this.getTitle()); // "Google"
});
casper.run();
Casper#mouseEvent(String type, String selector)
Added in 0.6.9 Triggers a mouse event on the first element found matching the provided selector.
Supported events are mouseup
, mousedown
, click
, mousemove
, mouseover
and mouseout
.
Example:
casper.start('http://www.google.fr/', function() {
this.mouseEvent('click', 'h2 a');
});
casper.run();
Casper#open(String location, Object Settings)
Performs an HTTP request for opening a given location. You can forge
GET
, POST
, PUT
, DELETE
and HEAD
requests.
Example for a standard GET
request:
casper.start();
casper.open('http://www.google.com/').then(function() {
this.echo('GOT it.');
});
casper.run();
Example for a POST
request:
casper.start();
casper.open('http://some.testserver.com/post.php', {
method: 'post',
data: {
'title': 'Plop',
'body': 'Wow.'
}
});
casper.then(function() {
this.echo('POSTED it.');
});
casper.run();
To pass nested parameters arrays:
casper.open('http://some.testserver.com/post.php', {
method: 'post',
data: {
'standard_param': 'foo',
'nested_param[]': [ // please note the use of square brackets!
'Something',
'Something else'
]
}
});
Added in 1.0
PhantomJS >= 1.6
You can also set custom request headers to send when performing an outgoing
request, passing the headers
option:
casper.open('http://some.testserver.com/post.php', {
method: 'post',
data: {
'title': 'Plop',
'body': 'Wow.'
},
headers: {
'Accept-Language': 'fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3'
}
});
Casper#reload([Function then])
Added in 1.0 Reloads current page location.
Example:
casper.start('http://google.com', function() {
this.echo("loaded");
this.reload(function() {
this.echo("loaded again");
});
});
casper.run();
Casper#repeat(int times, function then)
Repeats a navigation step a given number of times.
Example:
casper.start().repeat(3, function() {
this.echo("Badger");
});
casper.run();
Casper#resourceExists(Mixed test)
Checks if a resource has been loaded. You can pass either a function or a string to perform the test.
Example:
casper.start('http://www.google.com/', function() {
if (this.resourceExists('logo3w.png')) {
this.echo('Google logo loaded');
} else {
this.echo('Google logo not loaded', 'ERROR');
}
});
casper.run();
Note If you want to wait for a resource to
be loaded, use the waitForResource()
method.
Casper#run(fn onComplete[, int time])
Runs the whole suite of steps and optionally executes a callback when they've all been done. Obviously, calling this method is mandatory in order to run the Casper navigation suite.
Casper suite won't run:
casper.start('http://foo.bar/home', function() {
// ...
});
// hey, it's missing .run() here!
Casper suite will run:
casper.start('http://foo.bar/home', function() {
// ...
});
casper.run();
Casper.run()
also accepts an onComplete
callback, which you can
consider as a custom final step to perform when all the other steps have
been executed. Just don't forget to exit()
Casper if you define one!
casper.start('http://foo.bar/home', function() {
// ...
});
casper.then(function() {
// ...
});
casper.run(function() {
this.echo('So the whole suite ended.');
this.exit(); // <--- don't forget me!
});
Casper#sendKeys(Selector selector, String keys[, Object options])
Added in 1.0 Sends native keyboard events to the element matching the provided selector:
casper.then(function() {
this.sendKeys('form.contact input#name', 'Duke');
this.sendKeys('form.contact textarea#message', "Damn, I'm looking good.");
this.click('form.contact input[type="submit"]');
});
Casper#setHttpAuth(String username, String password)
Sets HTTP_AUTH_USER
and HTTP_AUTH_PW
values for HTTP based authentication
systems.
Example:
casper.start();
casper.setHttpAuth('sheldon.cooper', 'b4z1ng4');
casper.thenOpen('http://password-protected.domain.tld/', function() {
this.echo("I'm in. Bazinga.");
})
casper.run();
Of course you can directly pass the auth string in the url to open:
var url = 'http://sheldon.cooper:b4z1ng4@password-protected.domain.tld/';
casper.start(url, function() {
this.echo("I'm in. Bazinga.");
})
casper.run();
Casper#start(String url[, function then])
Configures and starts Casper, then open the provided url
and
optionally adds the step provided by the then
argument.
Example:
casper.start('http://google.fr/', function() {
this.echo("I'm loaded.");
});
casper.run();
Alternatively:
casper.start('http://google.fr/');
casper.then(function() {
this.echo("I'm loaded.");
});
casper.run();
Or alternatively:
casper.start('http://google.fr/');
casper.then(function() {
casper.echo("I'm loaded.");
});
casper.run();
Or even:
casper.start('http://google.fr/');
casper.then(function(self) {
self.echo("I'm loaded.");
});
casper.run();
Matter of taste!
Note You must call the start()
method
in order to be able to add navigation steps and run the suite. If you don't
you'll get an error message inviting you to do so anyway.
Casper#status(Boolean asString)
Added in 1.0 Returns the status of current Casper instance.
Example:
casper.start('http://google.fr/', function() {
this.echo(this.status(true));
});
casper.run();
Casper#then(Function fn)
This method is the standard way to add a new navigation step to the stack, by providing a simple function:
casper.start('http://google.fr/');
casper.then(function() {
this.echo("I'm in your google.");
});
casper.then(function() {
this.echo('Now, let me write something');
});
casper.then(function() {
this.echo('Oh well.');
});
casper.run();
You can add as many steps as you need. Note that the current Casper
instance
automatically binds the this
keyword for you within step functions.
To run all the steps you defined, call the run()
method,
and voila.
Note You must start()
the casper instance in order to use the then()
method.
Accessing the current HTTP response
Added in 1.0 You can access the current HTTP response object using the first parameter of your step callback:
casper.start('http://www.google.fr/', function(response) {
require('utils').dump(response);
});
That gives:
$ casperjs dump-headers.js
{
"contentType": "text/html; charset=UTF-8",
"headers": [
{
"name": "Date",
"value": "Thu, 18 Oct 2012 08:17:29 GMT"
},
{
"name": "Expires",
"value": "-1"
},
// ... lots of other headers
],
"id": 1,
"redirectURL": null,
"stage": "end",
"status": 200,
"statusText": "OK",
"time": "2012-10-18T08:17:37.068Z",
"url": "http://www.google.fr/"
}
So to fetch a particular header by its name:
casper.start('http://www.google.fr/', function(response) {
this.echo(response.headers.get('Date'));
});
That gives:
$ casperjs dump-headers.js
Thu, 18 Oct 2012 08:26:34 GMT
Casper#thenCLick(String selector)
Adds a new navigation step to click a given selector and add a new navigation step in a single operation.
Example:
// Querying for "Chuck Norris" on Google
casper.start('http://casperjs.org/').thenCLick('a', function() {
this.echo("I clicked on first link found, the page is now loaded.");
});
casper.run();
This method is basically a convenient a shortcut for chaining a
then()
and an evaluate()
calls.
Casper#thenEvaluate(Function fn[, Object replacements])
Adds a new navigation step to perform code evaluation within the current retrieved page DOM.
Example:
// Querying for "Chuck Norris" on Google
casper.start('http://google.fr/').thenEvaluate(function(term) {
document.querySelector('input[name="q"]').setAttribute('value', term);
document.querySelector('form[name="f"]').submit();
}, {
term: 'Chuck Norris'
});
casper.run();
This method is basically a convenient a shortcut for chaining a
then()
and an evaluate()
calls.
Casper#thenOpen(String location[, mixed options])
Adds a new navigation step for opening a new location, and optionally add a next step when its loaded.
Example:
casper.start('http://google.fr/').then(function() {
this.echo("I'm in your google.");
});
casper.thenOpen('http://yahoo.fr/', function() {
this.echo("Now I'm in your yahoo.")
});
casper.run();
Added in 1.0 You can also specify request settings by passing a setting object as the second argument:
casper.start().thenOpen('http://url.to/some/uri', {
method: "post",
data: {
username: 'chuck',
password: 'n0rr15'
}
}, function() {
this.echo("POST request has been sent.")
});
casper.run();
Casper#thenOpenAndEvaluate(String location[, function then, Object replacements])
Basically a shortcut for opening an url and evaluate code against remote DOM environment.
Example:
casper.start('http://google.fr/').then(function() {
this.echo("I'm in your google.");
});
casper.thenOpenAndEvaluate('http://yahoo.fr/', function() {
var f = document.querySelector('form');
f.querySelector('input[name=q]').value = 'chuck norris';
f.submit();
});
casper.run(function() {
this.debugPage();
this.exit();
});
Casper#toString()
Added in 1.0 Returns a string representation of current Casper instance.
Example:
casper.start('http://google.fr/', function() {
this.echo(this); // [object Casper], currently at http://google.fr/
});
casper.run();
Casper#userAgent(String agent)
Added in 1.0 Sets the User-Agent string to send through headers when performing requests.
Example:
casper.start();
casper.userAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X)');
casper.thenOpen('http://google.com/', function() {
this.echo("I'm a Mac.");
});
casper.userAgent('Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)');
casper.thenOpen('http://google.com/', function() {
this.echo("I'm a PC.");
});
casper.run();
Casper#viewport(Number width, Number height)
Changes current viewport size.
Example:
casper.viewport(1024, 768);
Note PhantomJS comes with a default viewport size of 400x300, and CasperJS doesn't override it by default.
Casper#visible(String selector)
Checks if the DOM element matching the provided selector expression is visible in remote page.
Example:
casper.start('http://google.com/', function() {
if (this.visible('#hplogo')) {
this.echo("I can see the logo");
} else {
this.echo("I can't see the logo");
}
});
Casper#wait(Number timeout[, Function then])
Pause steps suite execution for a given amount of time, and optionally execute a step on done.
Example:
casper.start('http://yoursite.tld/', function() {
this.wait(1000, function() {
this.echo("I've waited for a second.");
});
});
casper.run();
You can also write the same thing like this:
casper.start('http://yoursite.tld/');
casper.wait(1000, function() {
this.echo("I've waited for a second.");
});
casper.run();
Casper#waitFor(Function testFx[, Function then, Function onTimeout, Number timeout])
Waits until a function returns true to process any next step.
You can also set a callback on timeout using the onTimeout
argument,
and set the timeout using the timeout
one, in milliseconds. The
default timeout is set to 5000ms.
Example:
casper.start('http://yoursite.tld/');
casper.waitFor(function check() {
return this.evaluate(function() {
return document.querySelectorAll('ul.your-list li').length > 2;
});
}, function then() {
this.captureSelector('yoursitelist.png', 'ul.your-list');
});
casper.run();
Example using the onTimeout
callback:
casper.start('http://yoursite.tld/');
casper.waitFor(function check() {
return this.evaluate(function() {
return document.querySelectorAll('ul.your-list li').length > 2;
});
}, function then() { // step to execute when check() is ok
this.captureSelector('yoursitelist.png', 'ul.your-list');
}, function timeout() { // step to execute if check has failed
this.echo("I can't haz my screenshot.").exit();
});
casper.run();
Casper#waitForPopup(String|RegExp urlPattern[, Function then, Function onTimeout, Number timeout])
Added in 1.0 Waits for a popup having its url matching the provided pattern to be opened and loaded.
The currently loaded popups are available in the Casper.popups
array-like property.
casper.start('http://foo.bar/').then(function() {
this.test.assertTitle('Main page title');
this.clickLabel('Open me a popup');
});
// this will wait for the popup to be opened and loaded
casper.waitForPopup(/popup\.html$/, function() {
this.test.assertEquals(this.popups.length, 1);
});
// this will set the popup DOM as the main active one only for time the
// step closure being executed
casper.withPopup(/popup\.html$/, function() {
this.test.assertTitle('Popup title');
});
// next step will automatically revert the current page to the initial one
casper.then(function() {
this.test.assertTitle('Main page title');
});
Casper#waitForSelector(String selector[, Function then, Function onTimeout, Number timeout])
Waits until an element matching the provided selector expression exists in remote DOM to process any next step. Uses Casper.waitFor().
Example:
casper.start('https://twitter.com/#!/n1k0');
casper.waitForSelector('.tweet-row', function() {
this.captureSelector('twitter.png', 'html');
});
casper.run();
Casper#waitWhileSelector(String selector[, Function then, Function onTimeout, Number timeout])
Waits until an element matching the provided selector expression does not exist in remote DOM to process a next step. Uses Casper.waitFor().
Example:
casper.start('http://foo.bar/');
casper.waitWhileSelector('.selector', function() {
this.echo('.selector is no more!');
});
casper.run();
Casper#waitForResource(Function testFx[, Function then, Function onTimeout, Number timeout])
Wait until a resource that matches the given testFx
is loaded to
process a next step. Uses Casper.waitFor().
Example:
casper.start('http://foo.bar/', function() {
this.waitForResource("foobar.png");
});
casper.then(function() {
this.echo('foobar.png has been loaded.');
});
casper.run();
Another way to write the exact same behavior:
casper.start('http://foo.bar/');
casper.waitForResource("foobar.png", function() {
this.echo('foobar.png has been loaded.');
});
casper.run();
Casper#waitForText(String text[, Function then, Function onTimeout, Number timeout])
Added in 1.0 Waits until the passed text is present in the page contents before processing the immediate next step. Uses Casper.waitFor().
Example:
casper.start('http://why.univer.se/').waitForText("42", function() {
this.echo('Found the answer.');
});
casper.run();
Casper#waitUntilVisible(String selector[, Function then, Function onTimeout, Number timeout])
Waits until an element matching the provided selector expression is visible in the remote DOM to process a next step. Uses Casper.waitFor().
Casper#waitWhileVisible(String selector[, Function then, Function onTimeout, Number timeout])
Waits until an element matching the provided selector expression is no longer visible in remote DOM to process a next step. Uses Casper.waitFor().
Casper#warn(String message)
Logs and prints a warning message to the standard output.
casper.warn("I'm a warning message.");
Casper#withFrame(String frameName, Function then)
Added in 1.0 Switches the main page to the frame having the name matching the passed argument, and processes a step. The page context switch only lasts until the step execution is finished:
casper.start('tests/site/frames.html', function() {
this.test.assertTitle('FRAMESET TITLE');
});
casper.withFrame('frame1', function() {
this.test.assertTitle('FRAME TITLE');
});
casper.then(function() {
this.test.assertTitle('FRAMESET TITLE');
});
Casper#withPopup(Mixed popupInfo, Function step)
Added in 1.0 Switches the main page to a popup matching the information passed as argument, and processes a step. The page context switch only lasts until the step execution is finished:
casper.start('http://foo.bar/').then(function() {
this.test.assertTitle('Main page title');
this.clickLabel('Open me a popup');
});
// this will wait for the popup to be opened and loaded
casper.waitForPopup(/popup\.html$/, function() {
this.test.assertEquals(this.popups.length, 1);
});
// this will set the popup DOM as the main active one only for time the
// step closure being executed
casper.withPopup(/popup\.html$/, function() {
this.test.assertTitle('Popup title');
});
// next step will automatically revert the current page to the initial one
casper.then(function() {
this.test.assertTitle('Main page title');
});
Note: The currently loaded popups are available in the Casper.popups
array-like property.
Casper#zoom(Number factor)
Added in 1.0 PhantomJS >= 1.6 Sets the current page zoom factor.
var casper = require('casper').create();
casper.start().zoom(2).thenOpen('http://google.com', function() {
this.capture('big-google.png');
});
casper.run();
Quick reference
The Casper
class
options
back()
base64encode()
click()
clickLabel()
capture()
captureBase64()
captureSelector()
clear()
debugHTML()
debugPage()
die()
download()
each()
echo()
evaluate()
evaluateOrDie()
exists()
exit()
fetchText()
forward()
log()
fill()
getCurrentUrl()
getElementAttribute()
getElementBounds()
getElementsBounds()
getElementInfo()
getFormValues()
getGlobal()
getHTML()
getPageContent()
getTitle()
mouseEvent()
open()
reload()
repeat()
resourceExists()
run()
sendKeys()
setHttpAuth()
start()
status()
then()
thenClick()
thenEvaluate()
thenOpen()
thenOpenAndEvaluate()
toString()
userAgent()
viewport()
visible()
wait()
waitFor()
waitForPopup()
waitForSelector()
waitForResource()
waitForText()
waitUntilVisible()
waitWhileSelector()
waitWhileVisible()
warn()
withFrame()
withPopup()
zoom()
Client-side utils
Casper ships with a few client-side utilities which are injected in the
remote DOM environment, and accessible from there through the
__utils__
object instance of the ClientUtils
class of the
clientutils
module.
Note These tools are provided to avoid
coupling CasperJS to any third-party library like jQuery, Mootools or
something; but you can always include these and have them available client-side
using the Casper.options.clientScripts
option.
Bookmarklet
A bookmarklet is also available to help injecting Casper's client-side utilities in the DOM of your favorite browser.
Just drag this link
CasperJS utils
onto your favorites toobar; when clicking, a __utils__
object will
be available within the console of your browser.
Note CasperJS and PhantomJS being based on Webkit, you're strongly encouraged to use a recent Webkit compatible browser to use this bookmarklet (Chrome, Safari, etc…)
ClientUtils#echo(String message)
Added in 1.0 Print a message out to the casper console from the remote page DOM environment:
casper.start('http://foo.ner/').thenEvaluate(function() {
__utils__.echo('plop'); // this will be printed to your shell at runtime
});
ClientUtils#encode(String contents)
Encodes a string using the base64
algorithm. For the records,
CasperJS doesn't use builtin window.btoa()
function because it can't
deal efficiently with strings encoded using >8b characters.
var base64;
casper.start('http://foo.bar/', function() {
base64 = this.evaluate(function() {
return __utils__.encode("I've been a bit cryptic recently");
});
});
casper.run(function() {
this.echo(base64).exit();
});
ClientUtils#exists(String selector)
Checks if a DOM element matching a given selector expression exists.
var exists;
casper.start('http://foo.bar/', function() {
exists = this.evaluate(function() {
return __utils__.exists('#some_id');
});
});
casper.run(function() {
this.echo(exists).exit();
});
ClientUtils#findAll(String selector)
Retrieves all DOM elements matching a given selector expression.
var links;
casper.start('http://foo.bar/', function() {
links = this.evaluate(function() {
var elements = __utils__.findAll('a.menu');
return Array.prototype.forEach.call(elements, function(e) {
return e.getAttribute('href');
});
});
});
casper.run(function() {
this.echo(JSON.stringify(links)).exit();
});
ClientUtils#findOne(String selector)
Retrieves a single DOM element by a selector expression.
var href;
casper.start('http://foo.bar/', function() {
href = this.evaluate(function() {
return __utils__.findOne('#my_id').getAttribute('href');
});
});
casper.run(function() {
this.echo(href).exit();
});
ClientUtils#getBase64(String url[, String method, Object data])
This method will retrieved a base64 encoded version of any resource behind an url. For example, let's imagine we want to retrieve the base64 representation of some website's logo:
var logo = null;
casper.start('http://foo.bar/', function() {
logo = this.evaluate(function() {
var imgUrl = document.querySelector('img.logo').getAttribute('src');
return __utils__.getBase64(imgUrl);
});
});
casper.run(function() {
this.echo(logo).exit();
});
ClientUtils#getBinary(String url[, String method, Object data])
This method will retrieved the raw contents of a given binary resource; unfortunately though, PhantomJS cannot process these data directly so you'll have to process them within the remote DOM environment. If you intend to download the resource, use ClientUtils.getBase64() or Casper.base64encode() instead.
casper.start('http://foo.bar/', function() {
this.evaluate(function() {
var imgUrl = document.querySelector('img.logo').getAttribute('src');
console.log(__utils__.getBinary(imgUrl));
});
});
casper.run();
ClientUtils#getDocumentHeight()
Added in 1.0 Retrieves current document height.
var documentHeight;
casper.start('http://google.com/', function() {
documentHeight = this.evaluate(function() {
return __utils__.getDocumentHeight();
});
this.echo('Document height is ' + documentHeight + 'px');
});
casper.run();
Casper#getElementBounds(String selector)
Retrieves boundaries for a DOM element matching the provided selector.
It returns an Object with four keys: top
, left
, width
and height
, or
null
if the selector doesn't exist.
Casper#getElementsBounds(String selector)
Retrieves boundaries for all DOM element matching the provided selector.
It returns an array of objects each having four keys: top
, left
, width
and height
.
ClientUtils#getElementByXPath(String expression [, HTMLElement scope])
Retrieves a single DOM element matching a given XPath expression.
Added in 1.0
The scope
argument allow to set the context for executing the XPath query:
// will be performed against the whole document
__utils__.getElementByXPath('.//a');
// will be performed against a given DOM element
__utils__.getElementByXPath('.//a', __utils__.findOne('div.main'));
ClientUtils#getElementsByXPath(String expression [, HTMLElement scope])
Retrieves all DOM elements matching a given XPath expression, if any.
Added in 1.0
The scope
argument allow to set the context for executing the XPath query.
ClientUtils#getFieldValue(String inputName)
Added in 1.0
Retrieves the value from the field named against the inputNamed
argument:
Example:
<form>
<input type="text" name="plop" value="42">
</form>
__utils__.getFieldValue('plop'); // 42
ClientUtils#getFormValues(String selector)
Added in 1.0 Retrieves a given form all of its field values.
Example:
<form id="login" action="/login">
<input type="text" name="username" value="foo">
<input type="text" name="password" value="bar">
<input type="submit">
</form>
__utils__.getFormValues('form#login'); // {username: 'foo', password: 'bar'}
ClientUtils#mouseEvent(String type, String selector)
Dispatches a mouse event to the DOM element behind the provided selector.
Supported events are mouseup
, mousedown
, click
, mousemove
, mouseover
and mouseout
.
ClientUtils#removeElementsByXPath(String expression)
Removes all DOM elements matching a given XPath expression.
ClientUtils#sendAJAX(String url[, String method, Object data, Boolean async])
Added in 1.0 Sends an AJAX request, using the following parameters:
url
: The url to request.method
: The HTTP method (default:GET
).data
: Request parameters (default:null
).async
: Flag for an asynchroneous request? (default:false
)
Caveat
Don't forget to pass the --web-security=no
option in your CLI call in order to
perform cross-domains requests when needed.
Sample usage:
var data, wsurl = 'http://api.site.com/search.json';
casper.start('http://my.site.com/', function() {
data = this.evaluate(function(wsurl) {
return JSON.parse(__utils__.sendAJAX(wsurl, 'GET', null, false));
}, {wsurl: wsurl});
});
casper.then(function() {
require('utils').dump(data);
});
ClientUtils#visible(String selector)
Checks if an element is visible.
var logoIsVisible = casper.evaluate(function() {
return __utils__.visible('h1');
});
Colorizer
Casper ships with a colorizer
module which contains a Colorizer
class which can print stuff to the console output in color:
var colorizer = require('colorizer').create('Colorizer');
console.log(colorizer.colorize("Hello World", "INFO"));
Though most of the times you will use it transparently using the
Casper.echo()
method:
casper.echo('an informative message', 'INFO'); // printed in green
casper.echo('an error message', 'ERROR'); // printed in red
Skipping CasperJS styling operations
If you wish to skip the whole coloration operation and get uncolored plain text, just set the
colorizerType
casper option to Dummy
:
var casper = require('casper').create({
colorizerType: 'Dummy'
});
casper.echo("Hello", "INFO");
Note That's especially useful if you're using CasperJS on the Windows platform, as there's no support for colored output on this platform.
Available predefined styles
Available predefined styles are:
ERROR
: white text on red backgroundINFO
: green textTRACE
: green textPARAMETER
: cyan textCOMMENT
: yellow textWARNING
: red textGREEN_BAR
: white text on green backgroundRED_BAR
: white text on red backgroundINFO_BAR
: cyan text
Here's a sample output of what it can look like:
Colorizer#colorize(String text, String styleName)
Computes a colored version of the provided text string using a given predefined style.
var colorizer = require('colorizer').create();
console.log(colorizer.colorize("I'm a red error", "ERROR"));
Note
Most of the time you won't have to use a Colorizer
instance directly as CasperJS provides all the
necessary methods.
See the list of the predefined styles available.
Colorizer#format(String text, Object style)
Formats a text string using the provided style definition. A style
definition is a standard javascript Object
instance which can define
the following properties:
- String
bg
: background color name - String
fg
: foreground color name - Boolean
bold
: apply bold formatting - Boolean
underscore
: apply underline formatting - Boolean
blink
: apply blink formatting - Boolean
reverse
: apply reverse formatting - Boolean
conceal
: apply conceal formatting
Note Available color names are black
,
red
, green
, yellow
, blue
, magenta
, cyan
and white
.
var colorizer = require('colorizer').create();
colorizer.format("We all live in a yellow submarine", {
bg: 'yellow',
fg: 'blue',
bold: true
});
Tester
Casper ships with a tester
module and a Tester
class providing an
API for unit & functional testing purpose. By default you can access an
instance of this class through the test
property of any Casper
class
instance.
Note The best way to learn how to use the Tester API and see it in action is probably to have a look at the CasperJS test suite code.
Tester#assert(Boolean condition[, String message])
Asserts that the provided condition strictly resolves to a boolean
true
.
var url = 'http://www.google.fr/';
var casper = require('casper').create();
casper.start(url, function() {
this.test.assert(this.getCurrentUrl() === url, 'url is the one expected');
});
Tester#assertDoesntExist(String selector[, String message])
Asserts that an element matching the provided selector expression doesn't exists within the remote DOM environment.
var casper = require('casper').create();
casper.start('http://www.google.fr/', function() {
this.test.assertDoesntExist('form[name="gs"]', 'google.fr has a form with name "gs"');
});
Tester#assertEquals(mixed testValue, mixed expected[, String message])
Asserts that two values are strictly equals.
var url = 'http://www.google.fr/';
var casper = require('casper').create();
casper.start(url, function() {
this.test.assertEquals(this.getCurrentUrl(), url, 'url is the one expected');
});
Tester#assertEval(Function fn[, String message, Mixed arguments])
Asserts that a code evaluation in remote DOM
strictly resolves to a boolean true
.
casper.start('http://www.google.fr/', function() {
this.test.assertEval(function() {
return document.querySelectorAll('form').length > 0;
}, 'google.fr has at least one form');
this.test.assertEval(function(title) {
return document.title === title;
}, 'google.fr title is "Google"', 'Google');
});
Tester#assertEvalEquals(Function fn, mixed expected[, String message, Mixed arguments])
Asserts that the result of a code evaluation in remote DOM strictly equals to the expected value.
casper.start('http://www.google.fr/', function() {
this.test.assertEvalEquals(function() {
return document.querySelectorAll('form').length;
}, 1, 'google.fr provides a single form tag');
this.test.assertEval(function(title) {
return document.title;
}, 'Google', 'google.fr title is "Google"');
});
Tester#assertExists(String selector[, String message])
Asserts that an element matching the provided selector expression exists in remote DOM environment.
casper.start('http://www.google.fr/', function() {
this.test.assertExists('form[name="gs"]', 'google.fr has a form with name "gs"');
});
Tester#assertFalsy(Mixed subject[, String message])
Added in 1.0 Asserts that a given subject is falsy.
Tester#assertField(String inputName, String expected[, String message])
Asserts that a given form field has the provided value:
casper.start('http://www.google.fr/', function() {
this.fill('form[name="gs"]', { q: 'plop' }, false);
this.test.assertField('q', 'plop');
});
Added in 1.0.0
This also works with any input type: select
, textarea
, etc.
Tester#assertHttpStatus(Number status[, String message])
Asserts that current HTTP status code is the same as the one passed as argument.
casper.start('http://www.google.fr/', function() {
this.test.assertHttpStatus(200, 'google.fr is up');
});
Tester#assertMatch(mixed subject, RegExp pattern[, String message])
Asserts that a provided string matches a provided javascript RegExp
pattern.
casper.test.assertMatch('Chuck Norris', /^chuck/i, 'Chuck Norris' first name is Chuck');
Tester#assertNot(mixed subject[, String message])
Asserts that the passed subject resolves to some falsy value.
casper.test.assertNot(false, "Universe is still operational");
Tester#assertNotEquals(mixed testValue, mixed expected[, String message])
Added in 0.6.7 Asserts that two values are not strictly equals.
casper.test.assertNotEquals(true, "Truth is out");
Tester#assertNotVisible(String selector[, String message])
Asserts that the element matching the provided selector expression is not visible.
casper.start('http://www.google.fr/', function() {
this.test.assertNotVisible('h6');
});
Tester#assertRaises(Function fn, Array args[, String message])
Asserts that the provided function called with the given parameters
raises a javascript Error
.
casper.test.assertRaises(function(throwIt) {
if (throwIt) {
throw new Error('thrown');
}
}, [true], 'Error has been raised.');
casper.test.assertRaises(function(throwIt) {
if (throwIt) {
throw new Error('thrown');
}
}, [false], 'Error has been raised.'); // fails
Tester#assertSelectorDoesntHaveText(String selector, String text[, String message])
Asserts that given text does not exist in the provided selector.
casper.start('http://www.google.fr/', function() {
this.test.assertSelectorDoesntHaveText('title', 'Yahoo!');
});
Tester#assertSelectorExists(String selector[, String message])
Asserts that at least an element matching the provided selector expression exists in remote DOM.
casper.start('http://www.google.fr/', function() {
this.test.assertSelectorExists('form[name="gs"]', 'google.fr provides a form');
});
Tester#assertSelectorHasText(String selector, String text[, String message])
Asserts that given text exists in the provided selector.
casper.start('http://www.google.fr/', function() {
this.test.assertSelectorHasText('title', 'Google');
});
Tester#assertResourceExists(Function testFx[, String message])
The testFx
function is executed against all loaded assets and the test passes
when at least one resource matches.
casper.start('http://www.google.fr/', function() {
this.test.assertResourceExists(function (resource) {
return resource.url.match('logo3w.png');
}, 'google.fr logo was loaded');
// or shorter
this.test.assertResourceExists('logo3w.png', 'google.fr logo was loaded');
});
Check the documentation for Casper.resourceExists()
.
Tester#assertTextExists(String expected[, String message])
Asserts that body plain text content contains the given string.
casper.start('http://www.google.fr/', function() {
this.test.assertTextExists('google', 'page body contains "google"');
});
Tester#assertTextDoesntExist(String unexpected[, String message])
Added in 1.0 Asserts that body plain text content doesn't contain the given string.
casper.start('http://www.google.fr/', function() {
this.test.assertTextDoesntExist('bing', 'page body does not contain "bing"');
});
Tester#assertTitle(String expected[, String message])
Asserts that title of the remote page equals to the expected one.
casper.start('http://www.google.fr/', function() {
this.test.assertTitle('Google', 'google.fr has the correct title');
});
Tester#assertTitleMatch(RegExp pattern[, String message])
Asserts that title of the remote page matches the provided RegExp pattern.
casper.start('http://www.google.fr/', function() {
this.test.assertTitleMatch(/Google/, 'google.fr has a quite predictable title');
});
Tester#assertTruthy(Mixed subject[, String message])
Added in 1.0 Asserts that a given subject is truthy.
Tester#assertType(mixed input, String type[, String message])
Asserts that the provided input is of the given type.
casper.test.assertType(42, "number", "Okay, 42 is a number");
casper.test.assertType([1, 2, 3], "array", "Yeah, we can test for arrays too =)");
Tester#assertUrlMatch(Regexp pattern[, String message])
Asserts that a the current page url matches the provided RegExp pattern.
casper.start('http://www.google.fr/', function() {
this.test.assertUrlMatch(/^http:\/\//', 'google.fr is served in http://');
});
Tester#assertVisible(String selector[, String message])
Asserts that the element matching the provided selector expression is visible.
casper.start('http://www.google.fr/', function() {
this.test.assertVisible('h1');
});
Tester#colorize(String message, String style)
Render a colorized output. Basically a proxy method for
Casper.Colorizer#colorize()
.
Tester#comment(String message)
Writes a comment-style formatted message to stdout.
casper.test.comment("Hi, I'm a comment");
Tester#done([Number expected])
Flag a test file execution as being finished:
casper.test.assert(true);
casper.test.assertNot(false);
casper.test.done();
More asynchronously:
casper.start('http://mydomain.tld/', function() {
this.test.assertTitle('myTitle');
});
casper.thenClick('#logo', function() {
this.test.assertUrlMatches(/mydomain/);
});
casper.run(function() {
this.test.done();
});
Added in 1.0
The expected
parameter checks for an expected number of performed assertions:
casper.start('http://mydomain.tld/', function() {
this.test.assertTitle('myTitle');
});
casper.thenClick('#logo', function() {
this.test.assertUrlMatches(/mydomain/);
});
casper.run(function() {
this.test.done(2);
});
That's especially useful in case a given test script is abruptly interrupted leaving you with no obvious way to know it and an erroneously successful status.
Tester#error(String message)
Writes an error-style formatted message to stdout.
casper.test.error("Hi, I'm an error");
Tester#fail(String message)
Adds a failed test entry to the stack.
casper.test.fail("Georges W. Bush");
Tester#formatMessage(String message, String style)
Formats a message to highlight some parts of it. Only used internally by the tester.
Tester#getFailures()
Added in 1.0 Retrieves failures for current test suite.
casper.test.assertEquals(true, false);
require('utils').dump(casper.test.getFailures());
casper.test.done();
That will give something like this:
$ casperjs test test-getFailures.js
Test file: test-getFailures.js
FAIL Subject equals the expected value
# type: assertEquals
# subject: true
# expected: false
{
"length": 1,
"cases": [
{
"success": false,
"type": "assertEquals",
"standard": "Subject equals the expected value",
"file": "test-getFailures.js",
"values": {
"subject": true,
"expected": false
}
}
]
}
FAIL 1 tests executed, 0 passed, 1 failed.
Details for the 1 failed test:
In c.js:0
assertEquals: Subject equals the expected value
Tester#getPasses()
Added in 1.0 Retrieves a report for successful test cases in the current test suite.
casper.test.assertEquals(true, true);
require('utils').dump(casper.test.getPasses());
casper.test.done();
That will give something like this:
$ casperjs test test-getPasses.js
Test file: test-getPasses.js
PASS Subject equals the expected value
{
"length": 1,
"cases": [
{
"success": true,
"type": "assertEquals",
"standard": "Subject equals the expected value",
"file": "test-getPasses.js",
"values": {
"subject": true,
"expected": true
}
}
]
}
PASS 1 tests executed, 1 passed, 0 failed.
Tester#info(String message)
Writes an info-style formatted message to stdout.
casper.test.info("Hi, I'm an informative message.");
Tester#pass(String message)
Adds a successful test entry to the stack.
casper.test.pass("Barrack Obama");
Tester#renderResults(Boolean exit, Number status, String save)
Render tests results, save results in an XUnit formatted file, and optionally exit phantomjs.
var casper = require('casper').create();
// ...
casper.run(function() {
// exists with status code 0 and saves XUnit formatted results
// in test-results.xml
this.test.renderResults(true, 0, 'test-results.xml');
});
Note
This method is not to be called when using the
casperjs test
command, where it's done
automatically for you.
Quick reference
The Tester
class
assert()
assertDoesntExist()
assertEquals()
assertEval()
assertEvalEquals()
assertExists()
assertFalsy()
assertField()
assertHttpStatus()
assertMatch()
assertNot()
assertNotEquals()
assertNotVisible()
assertRaises()
assertResourceExists()
assertSelectorDoesntHaveText()
assertSelectorExists()
assertSelectorHasText()
assertTextExists()
assertTextDoesntExist()
assertTitle()
assertTitleMatch()
assertTruthy()
assertType()
assertUrlMatch()
assertVisible()
colorize()
comment()
done()
error()
fail()
formatMessage()
getFailures()
getPasses()
info()
pass()
renderResults()
Utils
The utils
module contains simple functions which circumvent some lacks in the
standard Javascript API.
Usage is pretty much straightforward:
var utils = require('utils');
utils.dump({plop: 42});
utils.betterTypeOf(input)
Provides a better typeof
operator equivalent, able to retrieve the Array
type.
utils.dump(value)
Dumps a JSON representation od passed argument onto the standard output. Useful for debugging.
utils.fileExt(file)
Retrieves the extension of passed filename.
utils.fillBlanks(text, pad)
Fills a string with trailing spaces to match pad
length.
utils.format(f)
Formats a string against passed args. sprintf
equivalent.
Note
This is a port of nodejs util.format()
.
utils.getPropertyPath(Object obj, String path)
Added in 1.0 Retrieves the value of an Object foreign property using a dot-separated path string:
var account = {
username: 'chuck',
skills: {
kick: {
roundhouse: true
}
}
}
utils.getPropertyPath(account, 'skills.kick.roundhouse'); // true
Beware, this function doesn't handle object key names containing a dot.
utils.inherits(ctor, superCtor)
Makes a constructor inheriting from another. Useful for subclassing and extending.
Note
This is a port of nodejs util.inherits()
.
utils.isArray(value)
Checks if passed argument is an instance of Array
.
utils.isCasperObject(value)
Checks if passed argument is an instance of Casper
.
utils.isClipRect(value)
Checks if passed argument is a cliprect
object.
utils.isFalsy(subject)
Added in 1.0 Returns subject falsiness.
utils.isFunction(value)
Checks if passed argument is a function.
utils.isJsFile(file)
Checks if passed filename is a Javascript one (by checking if it has a .js
or
.coffee
file extension).
utils.isNull(value)
Checks if passed argument is a null
.
utils.isNumber(value)
Checks if passed argument is an instance of Number
.
utils.isObject(value)
Checks if passed argument is an object.
utils.isString(value)
Checks if passed argument is an instance of String
.
utils.isTruthy(subject)
Added in 1.0 Returns subject truthiness.
utils.isType(what, type)
Checks if passed argument has its type matching the type
argument.
utils.isUndefined(value)
Checks if passed argument is undefined
.
utils.isWebPage(what)
Checks if passed argument is an instance of native PhantomJS' WebPage
object.
utils.mergeObjects(origin, add)
Merges two objects recursively.
utils.node(name, attributes)
Creates an (HT|X)ML element, having optional attributes
added.
utils.serialize(value)
Serializes a value using JSON format. Will serialize functions as strings. Useful for debugging and comparing objects.
utils.unique(array)
Retrieves unique values from within a given Array
.