CasperJS和警报框

CasperJS and alert boxes

本文关键字:CasperJS      更新时间:2023-09-26

如何测试页面上的警报框是否被调用?我可以获取警报框的文本并对其进行评估吗?

我在CasperJS中的点击是这样完成的:

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()"]');
});

UserLogin函数进行检查,在这种情况下,返回以下信息:

alert('Login has failed.');

我该如何检查?

您必须监听remote.alert事件:

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/);
});

尝试使其更加同步:

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);
});

1.1-beta4版本提供了casper.waitForAlert功能。有了它,当你需要对页面上的不同警报做出反应时,你可以编写更好的测试。