CasperJS and alerts

How to check that a warning window appears on my page? Can I take the text of the warning window and evaluate it?

My click in CasperJS is as follows:

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 to check it?

+5
source share
2 answers

You should listen to 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/);
});

Trying to make it somewhat 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);
});
+13
source

Version 1.1-beta4 provides a feature casper.waitForAlert. With it, you can write more pleasant tests when you need to respond to various warnings on the page.

+5
source

All Articles