Search code examples
javascriptangularjsprotractorangularjs-e2e

need protractor to wait for a service to return prior to testing


I am relatively new to protractor, and I have not been able to make protractor to wait for a page to unload prior to testing. Example below:

    //in loginPage object
    function login(email, password) {
        element(by.id('inputEmail')).sendKeys(email);
        element(by.id('inputPassword')).sendKeys(password);
        element(by.css('.btn.btn-primary')).click();
        browser.driver.sleep(4000);
        return !(element(by.binding('userCtrl.labels.signIn()')).isPresent());
    }

The sleep statement does not work however, as seen bu the below test always failing even when the login succeeds and the browser navigates away from the login page:

        //in separate test page
        it('should allow a valid user to login', function() {
            expect(loginPage.login('[email protected]', '12345678')).toBe(true);
        });

Thank you!


Solution

  • Protractor actions (e.g. isPresent()) return a promise, not the underlying value. i.e. this is a promise: element(by.binding('userCtrl.labels.signIn()')).isPresent()

    Please read this https://github.com/angular/protractor/blob/master/docs/control-flow.md.

    This should pass:

    function login(email, password) {
        element(by.id('inputEmail')).sendKeys(email);
        element(by.id('inputPassword')).sendKeys(password);
        element(by.css('.btn.btn-primary')).click();
        browser.driver.sleep(4000);
        return element(by.binding('userCtrl.labels.signIn()')).isPresent();
    }
    

    --

    //in separate test page
    it('should allow a valid user to login', function() {
        expect(loginPage.login('[email protected]', '12345678')).toBe(false);
    });
    

    What the expect did was unwrap the promise so that you can assert against its underlying value.