Question

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?

Was it helpful?

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).

OTHER TIPS

You may use the ExpectedConditions library now, which makes the code more readable:

function openAndCloseAlert () {
  var alertButton = $('#alertbutton');
  alertButton.click();

  // wait up to 1000ms for alert to pop up.
  browser.wait(protractor.ExpectedConditions.alertIsPresent(), 1000); 

  var alertDialog = browser.switchTo().alert();
  expect(alertDialog.getText()).toEqual('Hello');
  alertDialog.accept();
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top