How to wait for any element to appear in protractor

Viewed 12572

I am new in Protractor and having issues in putting wait statement My code is below:

element(by.xpath('html/body/app-root/div/app-dashboard/div/div/div[2]/div[1]/div/app-dashboard-filter/span/span/img')).click();

Before performing the click() operation I want protractor to wait for '/html/body/app-root/div/app-dashboard/div/div/div[1]/div[3]/div/div[1]/h5' element. This element comes in 4 seconds

After searching the INTERNET, I have tried below things:

1. browser.driver.sleep(5000);
2. browser.driver.manage().timeouts().setScriptTimeout(55000);
3. expect(element(by.xpath(/html/body/app-root/div/app-dashboard/div/div/div[1]/div[3]/div/div[1]/h5')).isPresent()).toBe(true);
4. browser.manage().timeouts().implicitlyWait(5000);

But due to one or the other error nothing worked for me. Please help!

3 Answers

You can do that in 2 ways.

  1. To see if element is visible in DOM.
  2. To see if element is visible in page.

1st point can be used if we use ng-if (since ng-if hides the element in DOM )

Example:-

var EC=protractor.ExpectedConditions;
browser.wait(EC.presenceOf(element),timeout,"Custom Error Message");

2nd point can be used in a normal way.

Example:-

var EC=protractor.ExpectedConditions;
browser.wait(EC.visibilityOf(element),timeout,"Custom Error Message");

Use visibility check & elementToBeClickable expected conditions, it works.Please find the code snippet below:

 var targetEle = element(by.xpath(/html/body/app-root/div/app-dashboard/div/div/div[1]/div[3]/div/div[1]/h5'));
    var EC_TIMEOUT = 5000;
    browser.wait(EC.visibilityOf(targetEle), EC_TIMEOUT).then(function(){
        browser.wait(EC.elementToBeClickable(targetEle), EC_TIMEOUT).then(function(){
            //callback();
            targetEle.click().then(function() {
                callback();
            });
        });
    });
Related