Function in selenium to return the desired element once it appears

Viewed 127

I'm trying to create a program to google search using selenium
based on this answer, so far the code looks like this

const { Builder, By, Key, until } = require('selenium-webdriver');

const driver = new Builder().forBrowser("firefox").build();

(async () => {
    await driver.get(`https://www.google.com`);

     var el = await driver.findElement(By.name('q'));
     await driver.wait(until.elementIsVisible(el),1000);
     await el.sendKeys('selenium');

     var el = await driver.findElement(By.name(`btnK`));
     await driver.wait(until.elementIsVisible(el),1000);
     await el.click();

    console.log('...Task Complete!')
})();

but writing

var el = await driver.findElement(By.something('...'));
     await driver.wait(until.elementIsVisible(el),1000);
     await el.do_something();

everytime becomes difficult so I tried to make a function like this:

const { Builder, By, Key, until } = require('selenium-webdriver');

const driver = new Builder().forBrowser("firefox").build();

async function whenElement(by_identity,timeout=1000){
  var el = await driver.findElement(by_identity);
  await driver.wait(until.elementIsVisible(el),timeout);
  return el;
}

(async () => {
    await driver.get(`https://www.google.com`);

     await whenElement(By.name('q')).sendKeys('selenium');

     await whenElement(By.name('btnK')).click();

    console.log('...Task Complete!')
})();

but it gives this ERROR:

UnhandledPromiseRejectionWarning: TypeError: whenElement(...).sendKeys is not a function

My aim is to reduce the number of variables and make it as simple as possible
so what exactly am I doing wrong here?

1 Answers

There seems to be an error with the promises. You can only invoke a function on the actual element returned by the Promise and not the promise itself. You must first wait for the promise that waits for the element whenElement to resolve and then you can use the element and wait for the promise returned by sendKeys to resolve.

const el = await whenElement(By.name('q'));
await el.sendKeys('selenium');

or

await (await whenElement(By.name('q'))).sendKeys('selenium');

or

await whenElement(By.name('q')).then(el => el.sendKeys('selenium'));
Related