Commit 967070c9 967070c9f3774071b75df78add6a50701b539fd8 by Nicolas Perriault

Merge pull request #748 from n1k0/wait-for-alert

Casper#waitForAlert()
2 parents 067d0cd0 2bc03233
......@@ -2025,6 +2025,19 @@ Example using the ``onTimeout`` callback::
``details`` is a property bag of various information that will be passed to the ``waitFor.timeout`` event, if it is emitted.
This can be used for better error messages or to conditionally ignore some timeout events.
.. index:: alert
``waitForAlert()``
-------------------------------------------------------------------------------
**Signature:** ``waitForAlert(Function then[, Function onTimeout, Number timeout])``
Waits until a `JavaScript alert <https://developer.mozilla.org/en-US/docs/Web/API/Window.alert>`_ is triggered. The step function will be passed the alert message in the ``response.data`` property::
casper.waitForAlert(function(response) {
this.echo("Alert received: " + response.data);
});
.. _casper_waitforpopup:
.. index:: Popups, New window, window.open, Tabs
......
......@@ -2118,6 +2118,31 @@ Casper.prototype.waitFor = function waitFor(testFx, then, onTimeout, timeout, de
};
/**
* Waits until any alert is triggered.
*
* @param Function then The next step to perform (required)
* @param Function onTimeout A callback function to call on timeout (optional)
* @param Number timeout The max amount of time to wait, in milliseconds (optional)
* @return Casper
*/
Casper.prototype.waitForAlert = function(then, onTimeout, timeout) {
"use strict";
if (!utils.isFunction(then)) {
throw new CasperError("waitForAlert() needs a step function");
}
var message;
function alertCallback(msg) {
message = msg;
}
this.once("remote.alert", alertCallback);
return this.waitFor(function isAlertReceived() {
return message !== undefined;
}, function onAlertReceived() {
this.then(this.createStep(then, {data: message}));
}, onTimeout, timeout);
};
/**
* Waits for a popup page having its url matching the provided pattern to be opened
* and loaded.
*
......
......@@ -23,3 +23,22 @@ casper.test.begin('alert events', 1, {
});
}
});
casper.test.begin("Casper.waitForAlert() waits for an alert", 1, function(test) {
casper.start().then(function() {
this.evaluate(function() {
setTimeout(function() {
alert("plop");
}, 500);
});
});
casper.waitForAlert(function(response) {
test.assertEquals(response.data, "plop",
"Casper.waitForAlert() can wait for an alert to be triggered");
});
casper.run(function() {
test.done();
});
});
......