How can I wait for a condition?

Muratso picture Muratso · Feb 27, 2014 · Viewed 72.5k times · Source

I'm new on protractor, and I'm trying to implement an e2e test. I don't know if this is the right way to do this, but... The page that I want to test is not a full angular page based, so... I'm having some trouble.

On my first spec I have:

describe('should open contact page', function() {
var ptor = protractor.getInstance();

beforeEach(function(){

   var Login = require('./util/Login');
   new Login(ptor);
});

I have created this Login class, but after login I want to open the contact page, but protractor immediately try to find element before the page is fully loaded.

I've tried to use:

browser.driver.wait(function() {

    expect(browser.findElement(by.xpath("//a[@href='#/contacts']")).isDisplayed());
    ptor.findElement(by.xpath("//a[@href='#/contacts']")).click();

});

But it doesn't work... it always try to find the element before the page loads. I tried this one too:

browser.driver.wait(function() {
    expect(ptor.isElementPresent(by.xpath("//a[@href='#/contacts']")));          
    ptor.findElement(by.xpath("//a[@href='#/contacts']")).click();
});

I'm able to do that using browser.sleep(); but I don't think that is a good option. Any idea? On my login class I have:

ptor.ignoreSynchronization = true;

How can I wait for this @href='#/contacts before protractor tries to click on it?

Answer

alecxe picture alecxe · Feb 23, 2015

Protractor 1.7.0 has also introduced a new feature: Expected Conditions.

There are several predefined conditions to explicitly wait for. In case you want to wait for an element to become present:

var EC = protractor.ExpectedConditions;

var e = element(by.id('xyz'));
browser.wait(EC.presenceOf(e), 10000);

expect(e.isPresent()).toBeTruthy();

See also: