Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using async and await in selenium protractor tests

Tags:

How do I use async and await in protractor tests?

it('test async', function(){
    var value = 0;
    function asyncAction() {
        return browser.driver.wait(()=>true)
            .then(function () {
                console.log('a');
                return value++;
            });
    }
    //-Problem Area-
    async function doAwait(){
        await asyncAction();
        return asyncAction();
    }

    doAwait();

    protractor.promise.controlFlow().execute( () => {
        console.log('b');
        expect(value).toBe(2);
    });
});

output here is

  • a
  • b
  • a

and value is 1 at time of expect function doAwait(){ await asyncAction(); return asyncAction(); }

I like to think of this as similar to

function doAwait(){
  asyncAction().then(()=>asyncAction());
}

Which works but the above async doAwait does not. I believe this is because the generator breaks the ControlFlow of selenium.

like image 746
TrevDev Avatar asked Aug 12 '16 19:08

TrevDev


1 Answers

Adding this to the protractor configuration works:

var webdriver = require.main.require('selenium-webdriver');
Promise = webdriver.promise.Promise;
Object.assign(Promise, webdriver.promise);
Promise.resolve = Promise.fulfilled;
Promise.reject = Promise.rejected;

Though maybe not all promises are supposed to be managed promises?

Worth noting that the other solution requires wrapping each async function:

protractor.promise.controlFlow().execute( async () => {
    await asyncAction();
    return asyncAction();
});
like image 99
TrevDev Avatar answered Oct 11 '22 15:10

TrevDev