javascriptwdiowdio-v6

Why we use await in front of wdio commands $ and $$


I am beginner to wdio(version 7 onwards). My question is why we put await in front of $(...) or $$(...) commands? $ and $$ retuns element object and array of elements respectively. Then why we use await in front of them? Are they returning promises?

Which of the following is correct?:

async getValue(){

return await $(some_selector).getText();
}

OR

async getValue(){

return (await $(some_selector)).getText();  //Note the paranthesis

}

Solution

  • WebDriver I/O uses, by default, an asynchronous model where all functions will be async. This means that all invocations return a promise and will need to be awaited before the result is available.

    In your comment on another user's answer you linked to the latest version (v8) of the docs where sync mode is officially deprecated but you tagged v6 in your question where sync mode is still supported but, again, not enabled by default.

    So, I guess, the answer to your question is a bit of both. Depending on whether you have sync mode enabled or not the functions return the elements directly or a promise that will resolve to the elements. All the examples assume that sync mode is not enabled and therefore need the async/await keywords.

    Promise Chaining

    From v7.9 onwards, WDIO supports promise chaining: https://blog.kiprosh.com/webdriverio-elements-chaining/

    With this in mind then example 1 would be the right implementation. Although version 2 could still be correct and returns the promise that will resolve eventually to the text contents but it doesn't looks right and should probably have an extra await in there, but the code is ugly with multiple awaits and it's not as easy to read the code.

    async getValue(){
      return await (await $(some_selector)).getText();
    }
    

    There's more information on promise chaining in WebdriverIO in the docs.