Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using async/await in IF statement

Tags:

protractor

I am new to protractor. I am currently writing a automation test using protractor to check if an element is enabled and perform on action only when the element is enabled. Following is my code. I want to use async / await but the test never gets inside the loop when i use async await. But the test passes even without executing. Please help.

if (await this.button.isEnabled()) {
  await this.text.sendKeys('abc');
  await this.send.click();
}
like image 934
asl Avatar asked Nov 14 '25 23:11

asl


2 Answers

for synchronizing if block and logic after if block. create an async function with the if logic inside it. like following

async a(){
  async function b() {
    if(condition){ 
      //await async call
      await new Promise((resolve, reject) => {
         setTimeout(function(){
            resolve("successful");
          }, 10000);
        });
      }
  }
  await b(); 
  console.log('now');
  //post if synchronous logic 
}

In above code "now" will be printed only after 10 secs. if you remove await before b(), "now" will be printed instantly before those 10 secs are over.

like image 194
omkarerudkar Avatar answered Nov 17 '25 21:11

omkarerudkar


Did you remember to declare your function async? This worked for me on my app:

async function doStuff() {
  if (await page.button.isEnabled()) {
    console.log('enabled');
  } else {
    console.log('disabled');
  }
}

doStuff();

This is unlikely necessary (I didn't need it), but in case you are running an older version of Protractor, you might have to disable the Selenium Promise Manager in your protractor.config:

exports.config = { 
  ...
  SELENIUM_PROMISE_MANAGER: false,
  ... 
};
like image 32
HaC Avatar answered Nov 17 '25 20:11

HaC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!