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?
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);
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With