protractor icon indicating copy to clipboard operation
protractor copied to clipboard

browser.switchTo().alert() no longer works as expected on dialogs

Open facultymatt opened this issue 12 years ago • 27 comments

Overview

I have a set of tests which rely on browser.switchTo().alert() to accept and dismiss both alerts and dialogs. The tests no longer work on the dialogs. The dialogs remain open, the test is not able to accept or dismiss the dialog, and the test control flow hangs.

// PASSES
it('should handle alerts', function() {
  // trigger $location.url('/page2');
  element(by.id('navigateAway')).click();
  var alertDialog = browser.switchTo().alert();
  expect(alertDialog.accept).toBeDefined();
  alertDialog.accept();
});

// FAILS
it('should handle dialogs', function() {
  // trigger window.onbeforeunload = function() { return 'are you sure?'; }
  browser.navigate().refresh();
  var alertDialog = browser.switchTo().alert();
  expect(alertDialog.accept).toBeDefined(); // fails
  alertDialog.accept(); // alertDialog and accept are not defined 
});

The full test suite is here

Investigation

There is discussion on the interwebs about similar problems where dialogs are not accessible by using browser.switchTo(). There is an open bug on selenium chromedriver here

There are a few related issues on protractor, specifically https://github.com/angular/protractor/issues/308 and https://github.com/angular/protractor/issues/55

I've tried using getAllWindowHandles and this fails too:

browser.getAllWindowHandles().then(function (handles) {
  browser.switchTo().window(handles[0]);
});

I've also tried rolling back to previous versions of protractor.

  • In protractor 1.0.0 the tests still fail, however the open dialog box is somehow ignored and doesn't block the control flow - all tests run and fail.
  • In 0.9.0 the tests fail AND block the control flow - the first failing test stops the remaining tests from running.

facultymatt avatar Nov 02 '14 13:11 facultymatt

I am still unable to use browser.switchTo().alert();

Tried everything and it is not related to chrome driver issue as same is working fine with webdriver-java native APIs. This is blocking usage of protractor and I am afraid I need to revert to webdriver - java API. Please update any luck on this??

vikasgahlaut avatar Jan 14 '15 10:01 vikasgahlaut

Have gone around in circles for a few days on this one, trying the various solutions and workarounds, but no luck. Was trying to put in a test for an unauthorised login. The (angular/Ionic) app pops up an access denied alert as expected and have been attempting to get protractor to deal with it using variants of browser.switchTo().alert() . One way out is to redesign the app to not use any alerting functionality for errors and confirmations (currently provided through $ionicPopup), but protractor really should be able to deal with alerts (and it sounds like it could in the past so something must have changed).

Fails for me in similar way with both Firefox and Chrome. The alert pops up in the browser, but is not found by protractor so it get's stuck.

Agree that this is blocking usage of protractor (which otherwise looks very handy).

Here are some of the attempts (inspired by various people's postings):

// A) the code below should deal with the ionic.Popup alert
// but fails to find it currently, so this is a bit broken
// for some reason (google "protractor NoSuchAlertError: no alert open")
// Seems to be a bug in protractor: https://github.com/angular/protractor/issues/1486

var alertDialog = browser.switchTo().alert();
expect(alertDialog.getText()).toEqual("unauthorized access");

// B) here is another attempt which did not quite work out either.
// 27 maps to bot.ErrorCode.NO_MODAL_DIALOG_OPEN: http://selenium.googlecode.com/git/docs/api/javascript/source/lib/atoms/error.js.src.html#l31
var alertDialog = browser.switchTo().alert().thenCatch(function (e) {
    if (e.code !== 27) { throw e; }
})
.then(function (alert) {
    if (alert) {
        expect(alertDialog.getText()).toEqual("unauthorized access");
        return alert.dismiss();
    }
});

// C) another attempt to solve the alert problem. No luck in finding the alert despite
// it being clearly present. Times out after 30 secs
// http://stackoverflow.com/questions/24037460/make-protractor-wait-for-an-alert-box
browser.wait(function() {
    return browser.switchTo().alert().then(
        function(alert) {
            expect(alert.getText()).toEqual("unauthorized access");
            alert.accept();
            return true;
            },
        function() { return false; }
    );
});

Using the javascript console in Chrome, I can directly find what I need from my app as per below, but not through protractor:

// from chrome javascript console, what we want is:
   document.getElementsByClassName("popup-body")[0].childNodes[0]
// which gives:
//   "<span>unauthorized access</span>"
// and the buttons are available from:
   document.getElementsByClassName("popup-buttons")

jhorrell avatar Feb 23 '15 09:02 jhorrell

Reason may be: You are working on angular app and navigating to non angular app, so if are stuck in alert after browser.get('someURL'), try using browser.driver.get('someURL'). This worked for me.

vikasgahlaut avatar Feb 23 '15 09:02 vikasgahlaut

In my case, everything happens within the angular app (the alert is raised by the sign-in page) so I don't think that will help.

jhorrell avatar Feb 23 '15 09:02 jhorrell

Having the same issue here.

Hacky workaround:

browser.executeScript("window.onbeforeunload = function(){};");

Above will close the onbeforenload created dialog, but obviously precludes the ability to test any associated logic and/or behavior related to it. Are there any updates on this issue or if/when it will be resolved?

skidvd avatar Apr 10 '15 13:04 skidvd

I have a similar issue. But the strange part is that only one test fails, the rest run and pass with no problems. The message I get is slightly different though: "Failed: no alert open".

denislins avatar Apr 29 '15 14:04 denislins

Are there any updates on this issue? Facing the exact same problem here...

yonirab avatar Jun 01 '15 14:06 yonirab

I found that this can be caused by two dialogs being opened in quick succession - the second one not being found by webdriver in time. A workaround was to put a short sleep in before trying to access the alert box...

browser.navigate().refresh();
browser.sleep(100);
var alertDialog = browser.switchTo().alert();

petebacondarwin avatar Jul 26 '15 07:07 petebacondarwin

This worked for me:

Protractor e2e failures with alert - Pete worked with Hank Duan to resolve this. It turned out it was an incorrect use of Protractor. See addb1ae37.

From 27 July 2015 AngularJS 1.x Meeting Notes

ndrsv avatar Aug 05 '15 04:08 ndrsv

I have a popup that opens on browser refresh. Try as I might, it doesn't go away when calling browser.switchTo().alert().accept();. Instead all subsequent tests fail with Failed: unexpected alert open: {Alert text : XXX}. This is what my code looks like right now:

browser.refresh();
browser.wait(protractor.ExpectedConditions.alertIsPresent(), 1000);
browser.switchTo().alert().accept();

ghost avatar Feb 17 '16 11:02 ghost

I know I am late to the party, however, I have a solution that might help make this work without the ExpectedConditions, hope this helps:

function () {
  webdriverJS.sleep(testData.timeOuts.salesforceWindowPopupTimeout);

  var handlePromise = browser.getAllWindowHandles();
  browser.ignoreSynchronization = true;
  handlePromise.then(function(handles) {
    var handleNum = 0;
    for (var i=0; i < handles.length; i++) {
      webdriverJS.switchTo().window(handles[i]).then(function () {

        webdriverJS.getCurrentUrl().then(function (url) {

          webdriverJS.getTitle().then(function (title) {
            if (/titleRegex/.test(title) && /urlRegex/.test(url)) {
              handleNum = i;
              console.log("Title #: " + title);
              console.log("URL #: " + url);
            }
          });

          if (/print/.test(url)) {
            var body = element(by.tagName("body"));
            body.sendKeys(protractor.Key.ESCAPE);
          }

        });
      });
    }
    webdriverJS.switchTo().window(handles[handleNum]);
  });
};

trupti11 avatar Mar 09 '16 18:03 trupti11

You should put a catch handler onto the navigate and place your expect/check code there:

            browser.navigate().refresh().catch(function() {
                return browser.switchTo().alert().then(function (alert) {
                      // Is this expected?
                });
            });

You cannot do:

browser....navigate to somewhere
... go and get alert box and do something

As the exception has ALREADY been thrown and your test has failed.

inthegarage avatar Jul 08 '16 10:07 inthegarage

The external issue has been closed as stale, and I think that this bug is probably too stale to be useful anymore. Closing. Please open a new issue if you are still experiencing a reproducible bug!

juliemr avatar Jul 14 '16 00:07 juliemr

I'm still experiencing this bug... do I really need to open a new bug report?

niieani avatar Jul 14 '16 00:07 niieani

For me this is fixed in Chrome and FireFox, @niieani is this an IE issue? If so the associated bug above will help you ( #3146).

inthegarage avatar Jul 14 '16 08:07 inthegarage

I'll go back to my code and try to be more specific ASAP, @inthegarage.

niieani avatar Jul 14 '16 09:07 niieani

@niieani I've done a bit of research and signs are pointing to Chrome 52's release as of last week.

All of my chrome tests have been failing, regardless of branch, since that time. The only shared dependency in our CI pipeline is 1) protractor (unchanged), 2) selenium (unchanged) and 3) chrome (updated).

It may be worth investigating further.

Droogans avatar Jul 25 '16 20:07 Droogans

I'm experiencing this as well, and have also noticed that 52 is also no longer throwing UnhandledAlertException. I've logged issue 632024 at Chromium, which may be related. Feel free to star it if you agree...

ghost avatar Jul 27 '16 18:07 ghost

After the release of chrome 52 about 2-3 weeks ago we have experienced a large number of failures in our selenium GUI tests. Rolling back to the latest chrome 51 version solved this issue for us.

I will be looking further into how the behavior differs in chrome 51 vs 52.

DavidDDamato avatar Jul 28 '16 15:07 DavidDDamato

I was able to clear up many of the issues I was experiencing by updating ChromeDriver to 2.22, Selenium.WebDriver to 2.53.1 (from 2.53.0).

ghost avatar Jul 28 '16 16:07 ghost