Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CasperJS and alert boxes

How do I test that an alert box on my page was called? Can I grab the text of the alert box and evaluate it?

My click in CasperJS is done like this:

casper.waitForSelector('a[href="javascript:UserLogin()"]',
    function success() {
        this.test.comment("Submiting the bad login info");
        this.test.assertExists('a[href="javascript:UserLogin()"]');
        this.click("a#h_login");
    },
    function fail() {
        this.test.assertExists('a[href="javascript:UserLogin()"]');
});

The UserLogin function checks and in this case, returns this:

alert('Login has failed.');

How do I check this?

like image 633
cdub Avatar asked Feb 04 '13 22:02

cdub


2 Answers

You have to listen to the remote.alert event:

casper.on('remote.alert', function(message) {
    this.echo('alert message: ' + message);
    // or if you want to test it
    this.test.assertMatch(message, /Login has failed/);
});

An attempt to make it a bit more synchronous:

function testAlert(message) {
    this.test.assertMatch(message, /Login has failed/);
}

casper.then(function() {
    // temporarily registering listener
    this.on('remote.alert', testAlert);
});

casper.waitForSelector('#login', function success() {
    this.test.pass('selector was found');
    this.click("#login");
}, function fail() {
    this.test.fail('selector was found');
});

casper.then(function() {
    this.removeListener('remote.alert', testAlert);
});
like image 61
NiKo Avatar answered Sep 24 '22 22:09

NiKo


Version 1.1-beta4 provides the casper.waitForAlert function. With it you can write nicer tests when you need to react to different alerts on the page.

like image 43
Artjom B. Avatar answered Sep 21 '22 22:09

Artjom B.