Make Protractor wait for an alert box?

angularjs, protractor

Solution

I solved similar task with the following statement in my Protractor test:

browser.wait(function() {
    return browser.switchTo().alert().then(
        function() { return true; }, 
        function() { return false; }
    );
});

In general, this code constantly tries to switch to an alert until success (when the alert is opened at last). Some more details: "browser.wait" waits until called function returns true. "browser.switchTo().alert()" tries to switch to an opened alert box and either has success, or fails. Since "browser.switchTo().alert()" returns a promise, then the promise either resolved and the first function runs (returns true), or rejected and the second function runs (returns false).

Problem

I am writing E2E tests for a log in page. If the log in fails, an alert box pops up informing the user of the invalid user name or password. The log in itself is a call to a web service and the controller is handling the callback. When I use `browser.switchTo().alert();` in Protractor, it happens before the callback finishes. Is there a way I can make Protractor wait for that alert box to pop up?

Original source