HenrikBechmann
HenrikBechmann

Reputation: 621

afterEach not waiting to complete before continuing

I use afterEach to logout, but my tests try to login before afterEach completes logging out.

I'm trying to avoid the use of sleep statements (really slows things down).

How can I get a test to wait for the previous beforeEach to finish?

code snippets:

afterEach(function() {
    AccountBlock.logout().then(function(){
        browser.sleep(2000); // I want to get rid of this
    });
});

the logout() method (from the AccountBlock object):

this.logout = function() {
    var logoutLink = this.logoutLink;
    var userName = this.userName;
    return logoutLink.isDisplayed().then(function(isDisplayed){
        if (!isDisplayed) {
            return userName.click().then (function() {
                return logoutLink.click();
            }); // open the account menu before logout
        } else { // account menu already displayed
            return logoutLink.click();
        }
    });
}
this.userName = element(by.css('a[ng-bind="userName"]'));
this.logoutLink = element(by.css('a[ng-click^="logout"]'));

Upvotes: 1

Views: 1092

Answers (2)

Nortain
Nortain

Reputation: 143

browser.wait is definitely the way to go but rather than calling on elements directly to ask if they are present or displayed protractor has built-in functionality for just this called ExpectedConditions. You can use this let protractor force the browser to wait until it has met it's own expected conditions.

Below I am finding the element, using expected conditions to detect the presence of the element then using the not operator to detect when the element is no longer present. This should force browser.wait to pause future promises until that condition is true.

afterEach(function(){
    var ec = protractor.ExpectedConditions;
    var logout = element(by.css('a[ng-click^="logout"]'));
    var logoutLink = ec.presenceOf(logout);
    var logoutLinkNotThereAnymore = ec.not(logoutLink);

    //do logout
    browser.wait(logoutLinkNotThereAnymore, 10000, "Waited 10 seconds");
});

beforeEach(function(){
    //do login
});

Upvotes: 1

JoMendez
JoMendez

Reputation: 884

I use browser.wait() to avoid sleep(), in your login block of code you can do this

   var doLogin = function(){
           browser.wait(element(by.id('yourLoginBoxId')).isDisplayed); //this will wait until the html with the form to login is in your DOM
          //your code to login here
      };

note that isDisplayed doesn't have the ().

Upvotes: 0

Related Questions