nodejs selenium add a function to webdriver (highlight element) click() is not a function

Viewed 356

trying to create a new function in chromedriver or override existing findelement() function

First steps for me was create new instead of override to test it

 const driver = await new Builder()
  .forBrowser("chrome")
  .setChromeOptions(
      new chrome.Options()
          .windowSize(screen)
          )
  .build();
  driver.findElementWithHighlight = async (locator) => {
    let element = await driver.findElement(locator);
    await driver.executeScript("arguments[0].style.border='3px solid red'", element);
    return driver.findElement(locator);
  };

then in another function I call

await driver.findElementWithHighlight(some locator).click();

but after all this I get this error:

TypeError: driver.findElementWithHighlight(...).click is not a function

What do I do wrong here? Why my new function do not have click() method if it returns same WebElementPromise?

2 Answers

It returns a promise and you are calling the .click() on the Promise object. Instead wrap it around (await driver.findElementWithHighlight(...)).click(). So It will be awaited and you will be able to call your click function.

You can keep making more functions

driver.findElementWithHighlight = async (locator) => {
    let element = await driver.findElement(locator);
    await driver.executeScript("arguments[0].style.border='3px solid red'", element);
    return driver.findElement(locator);
};
driver.findElementWithHighlightAndClick = async (locator) => {
    return driver.findElementWithHighlight(locator)
        .then((highlighted) => {
            return highlighted.click();
        });
};

driver.findElementWithHighlightAndClick(some_locator);
Related