CasperJS code examples for 23rd January 2015 Workshop

These are the code examples that appear in the presentation held at the CasperJS Workshop in 23rd January 2015, in Espoo, Finland.

They are offered here for easier copying, since the snippets shown in the presentation are screen captures.

There is no warranty.

A typical CasperJS script

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

casper.start('https://casperjs.org/', function() {
    this.echo(this.getTitle());
});

casper.thenOpen('https://phantomjs.org', function() {
    this.echo(this.getTitle());
});

casper.thenOpen('https://slimerjs.org', function() {
    this.echo(this.getTitle());
});

casper.run();

Run with the command casperjs casper-typical.js. The output should be something similar to:

CasperJS, a navigation scripting and testing utility for PhantomJS and SlimerJS
PhantomJS | PhantomJS
SlimerJS

Utility module example

Documentation for the utils module.

var utils = require('utils');
var casper = require('casper').create();

casper.start('https://microsoft.com/', function(response) {
    utils.dump(response.headers);
});

casper.run();

The expected output is something similar to:

[
    {
        "name": "Cache-Control",
        "value": "private"
    },
    {
        "name": "Content-Type",
        "value": "text/html"
    },
    {
        "name": "Content-Encoding",
        "value": "gzip"
    },

File system module example

Documentation for the fs module in the PhantomJS API.

var fs = require('fs');
var casper = require('casper').create();

casper.start('https://microsoft.com/', function(response) {
    var stream = fs.open('microsoft-response.json', 'w');
    stream.write(JSON.stringify(response, null, '  '));
    stream.close();
});

casper.run();

Expect no output but there should appear a file called microsoft-response.json, which has the same content for headers as shown by the previous example.

In addition the file should contain things like:

{
  "contentType": "text/html",
  "headers": [],
  "id": 3,
  "redirectURL": null,
  "stage": "end",
  "status": 200,
  "statusText": "OK",
  "time": "2015-01-22T13:29:31.940Z",
  "url": "https://www.microsoft.com/fi-fi/default.aspx",
  "data": null
}

Evaluate a function in the page context

Documentation for the evaluate() method.

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

casper.start('https://paazmaya.fi/', function(response) {
    var version = this.evaluate(function() {
        return $.fn.jquery;
    });
    this.echo('jQuery version: ' + version);
});

casper.run();

The output should look something similar to:

jQuery version: 2.1.3

Assert evaluation example

Documentation for the assertEval() method.

Note that while using the test framework, there is no need to initialise the casper instance as in the previous examples.

casper.test.begin('At least jQuery 2.1 test', 1, function(test) {
    casper.start('https://paazmaya.fi/').then(function() {
        test.assertEval(function() {
            var ver = $.fn.jquery.split('.');
            return ver[0] > 2 || (ver[0] == 2 && ver[1] >= 1);
        }, 'Page has at least jQuery version 2.1');
    }).run(function() {
        test.done();
    });
});

Run with casper test casper-assert-evaluate.js. The output could be something similar to:

Test file: casper-assert-evaluate.js
# At least jQuery 2.1 test
PASS Page has at least jQuery version 2.1
PASS 1 test executed in 2.909s, 1 passed, 0 failed, 0 dubious, 0 skipped.

Please note that by using PhantomJS 1.9.8, the following warning is printed, but it can be safely ignored. There is an issue for it.

Unsafe JavaScript attempt to access frame
with URL about:blank from frame with URL
file:///usr/local/Cellar/casperjs/1.1-beta3/libexec/bin/bootstrap.js.
Domains, protocols and ports must match.

Assert resource example

Test to see if a given resource was loaded.

Documentation for the assertResourceExists() method.

var url = 'https://www.microsoft.com/en-us/mobile/phone/lumia635/specifications/';

casper.test.begin('Changing the product image from color options', 2, function(test) {
    casper.start(url, function() {
        this.viewport(1280, 900);
    }).then(function () {
        test.assertResourceExists(function(resource) {
            return resource.url.match('Lumia-635-White-new-spec-png.png');
        }, 'White image existed on default');
    }).then(function () {
        this.click('#variant-3');
        this.wait(300, function() {
            test.assertResourceExists(function(resource) {
                return resource.url.match('Lumia-635-Cyan-Front-png.png');
            }, 'Cyan image appeared after click event');
        });
    }).run(function() {
        test.done();
    });
});

Run with casperjs test casper-assert-resource.js. The output on success would be something similar to:

Test file: casper-assert-resource.js
# Changing the product image from color options
PASS White image existed on default
PASS Cyan image appeared after click event
PASS 2 tests executed in 4.88s, 2 passed, 0 failed, 0 dubious, 0 skipped.

While in the case of failing, for example on slow Internet connection where the 300 millisecond wait is not enough:

Test file: casper-assert-resource.js
# Changing the product image from color options
PASS White image existed on default
FAIL Cyan image appeared after click event
#    type: assertResourceExists
#    file: casper-assert-resource.js:16
#    code: }, 'Cyan image appeared after click event');
#    subject: false
#    test: undefined
FAIL 2 tests executed in 4.693s, 1 passed, 1 failed, 0 dubious, 0 skipped.

Details for the 1 failed test:

In casper-assert-resource.js:16
  Changing the product image from color options
    assertResourceExists: Cyan image appeared after click event

Screen capture example

Documentation for the capture() method.

var casper = require('casper').create({
    viewportSize: {
        width: 800,
        height: 800
    }
});

casper.start('https://codepen.io/mr_alien/full/GLIjo/', function() {
    this.capture('best-casperjs-student.png');
});

casper.thenOpen('https://codepen.io/tvolodimir/full/wqKuJ/', function() {
    this.wait(Math.random() * 2000 + 2000, function() {
        this.capture('valentines-day-is-soon.png');
    });
});

casper.run();

There should appear two PNG images in the current folder, both with 800 times 800 pixels resolution.

Thank you for your patience.