How to wait for when an element is removed from DO

2019-03-19 18:10发布

问题:

I run into this issue whenever I try to wait until an DOM element is removed from the current DOM tree on the web page that my protractor test is testing. I already got a hang of it when I try to wait until a DOM element becomes hidden with this nice technique offered by user2912739 in another thread.

var el = element(by.css('.your-css-class'));
return browser.wait(protractor.until.elementIsNotVisible(el));

This works pretty decent. However, when it comes to waiting for an element got removed from the DOM tree both .isDisplayed() and .isPresent() or the above lines do NOT seem to work. The test would continue run but it appears like it is trying to get that element but never succeeds so it eventually timed out based on the timeout setting the configuration file. For example. this is the log.

timeout: timed out after 30000 msec waiting for spec to complete

The use case of this can be quite frequent whenever you are dealing with testing if an element is removed from the DOM tree, for instance, a modal that is closed and removed from the page when user click actions that dismisses that modal element, or an element that you just want to "delete" so that it no longer exists on the page. So, in the test, you just want to continue the test run as soon as it is removed from DOM tree.

I've searched through protractor and web driver api, and it seems there is no api that does this job.

回答1:

not sure where you got protractor.until from as that's not part of the core library. This is how you would do it with protractor:

var el = element(by.css('.your-css-class'));
return browser.wait(function() {
  return el.isPresent().then(function(present) {
    return !present;
  })
});

Once feat(expectedConditions) is in (probably protractor 1.7), you can do:

var EC = protractor.ExpectedConditions;

var el = element(by.css('.your-css-class'));
return browser.wait(EC.not(EC.presenceOf(el)));