Tips for waiting for an HTML element to load in a Selenium JavaScript testing script

I'm struggling to find a way to wait for an element to load in a javascript selenium test script. The closest thing I've come across is until.elementLocated, but it seems to throw an immediate exception.

Is there a method to delay throwing the "NoSuchElementError" exception until the timeout has expired?

"NoSuchElementError: no such element: Unable to locate element: {"method":"xpath","selector":"//button[text()='NEXT']"}"

Or is there any way to avoid this exception altogether when waiting for an element in Selenium?

  await driver.wait(function () {
        let text = "//button[text()='" + "NEXT" + "']";
        let button = By.xpath(text);
        return until.elementLocated(button);
    }, 40000).then(() => {console.log("element is located")})

Answer №1

My primary focus is on utilizing Selenium with Java or Python, while I also delve into JS using Puppeteer or Playwright. As a result, I have not yet tested the initial solution (although I am confident it would be effective).

Based on the documentation, driver.wait requires a function and waits for its condition to become true. Therefore, you can utilize findElements which does not generate exceptions and wait for the length of the returned collection to exceed 0.

const getElements = (locator) => driver.findElements(locator).then(els => els.length);
await driver.wait(() => getElements(By.xpath("//button[text()='NEXT']")), 10000);

If needed, you can create your own custom waiter that will wait for a condition to be true and return an element. While this approach may not be as clean, it is adaptable across different frameworks.

const waitFor = async (action, timeoutMs, pollIntervalMs) => {
  let isTimeout = false;
  const timeoutId = setTimeout(() => {
    isTimeout = true;
  }, timeoutMs);
  let result;
  while (!isTimeout && !result) {
    result = await action();
    await new Promise(resolve => setTimeout(resolve, pollIntervalMs));
  }

  clearTimeout(timeoutId);
  if (isTimeout) {
    throw new Error('Timeout exceeded!');
  } else {
    return result;
  }
};

const getElementOrNull = (locator) => driver.findElements(locator).then(els => els.length ? els[0] : null);

const element = await waitFor(() => getElementOrNull(By.xpath("//button[text()='NEXT']")), 10000, 500);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Selenium Webdriver to Interact with Banners

Struggling to click on the rotating < and > buttons in a banner on amazon.in, even after several attempts. Although I have written the following code, it doesn't seem to work: driver.get("amazon.in"); driver.manage().timeouts().implicitlyWait( ...

Utilize Jquery to easily interact with RadComboBoxes

Is there a way to capture all RadComboBoxes change events in JQUERY for ASP.NET? $("input[type='text']").Change(function() { alert('changed'); }); In this example, I am specifying the input type as "text" because RadComboBoxes hav ...

Setting the max.retries system property in Thucydides: A step-by-step guide

Could someone provide instructions on how to set the system property max.retries in Thucydides? I want to be able to rerun failed tests in Thudcydies using the max.retries feature. Any guidance on how to do this would be greatly appreciated. ...

How to send arguments to a callback function in Next.JS

Here's the code snippet I'm working with: import Router from "next/router"; import React from "react"; export default function MainIndex() { return (<React.Fragment> <h1>Main Index Page</h1> ...

HTML Elements for Displaying Undefined JSON Information

Hey there, I'm new to programming and I'm looking to display JSON data in an HTML table using jQuery. The issue I'm facing is that the output from the server shows up as 'undefined'. My goal is to have a constantly updated list of ...

How can I make my modal box appear after someone clicks on selecting a college?

Can someone help me figure out how to display my modal box after clicking into the selecting list? I've already coded it, but I'm struggling with getting it to show up after the click event. Any assistance is appreciated! In the image provided, ...

Leveraging random attributes in Next.js without encountering the "server/client mismatch" issue

Is there a way to generate unique IDs for form inputs dynamically, in order to avoid conflicts with other elements that share the same ID? If multiple login forms are present on a single page, each with an 'email' field, setting the id property b ...

Uncover the solution to eliminating webpack warnings associated with incorporating the winston logger by utilizing the ContextReplacementPlugin

When running webpack on a project that includes the winston package, several warnings are generated. This is because webpack automatically includes non-javascript files due to a lazy-loading mechanism in a dependency called logform. The issue arises when ...

Component fails to trigger @click handler

.vue component <template> <div class="modal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> Loading Files </div> < ...

The "keydown" event in React will not alter the state

I am currently developing an application that requires me to track the keys pressed by the user. I am utilizing keydown and keyup events for this purpose. However, I am facing a challenge where I do not want the same key to be registered multiple times whe ...

Issue encountered while constructing my application (utilizing the "yarn run build" command and in Vercel)

Encountered an error during the build process, whether on the server or locally. This issue arises when using package managers like yarn, npm, and others. The error specifically points to a problem in the CSS file, but it only occurs in the production bu ...

Incorrectly resolving routes in the generate option of Nuxt JS's .env configuration file

Having trouble using Nuxt JS's 2.9.2 generate object to create dynamic pages as static files by referencing a URL from my .env file: nuxt.config.js require('dotenv').config(); import pkg from './package' import axios from 'a ...

Retrieve the desired element from an array when a button is clicked

When I click on the button, I need to update an object in an array. However, I am facing difficulties selecting the object that was clicked. For better readability, here is the link to my GitHub repository: https://github.com/Azciop/BernamontSteven_P7_V2 ...

Encountering an error message while trying to use `npm i`

I am attempting to set up the environment in order to run tests on JavaScript. I am using Windows 10 and Python 2.7. However, when I input the command 'npm -i', I receive an error message: https://i.stack.imgur.com/j2WXE.jpg To try and resolve ...

What is the method to effectively conduct a testing procedure for JavaScript files that have been exported using

I have a JavaScript file called "sum.js" which contains a simple function: // sum.js function sum(a, b) { return a + b; } export default { sum }; Now I want to write a test for this file using Jest. Here is my "sum.test.js" file in the same folder: // ...

Issue with incremental static generation in version 13 not functioning as expected

Is ISR working for anyone in the NextJS 13 Beta version? I have set revalidate to 15 as follows. export const revalidate = 15; However, even after running `npm run build`, the page still remains a statically generated site (SSG). The symbol is showing u ...

Upon loading, make sure to click on the link located within the third <li> tag

I am working with a list (<ul>): <ul class="options_inner"> <li><a data-dk-dropdown-value=".option1"></a></li> <li><a data-dk-dropdown-value=".option2"></a></li> <li><a data- ...

What is the best way to make a CSS element move with Javascript?

Currently working on a JavaScript game where I am in need of a CSS object to replace the original JavaScript object. Specifically, I want my "sword" CSS object to move along with my player object when it is Unsheathead. All the examples I find only show wh ...

Guide on how to retrieve Twitter Username and Profile Photo through the Twit NPM Package

Utilizing the twit npm package to retrieve the Authenticated Twitter Username and Profile Image, here is the code I am using: const Twit = require('twit'); let T = new Twit({ consumer_key: 'xxx', ...

Changing the Color of an Object3D Mesh in Three.js

Seeking advice on how to update the color of a Three.js Object3D. Initially created using MeshStandardMaterial, this object is later retrieved from the scene by its ID. Is it possible to change the color of the Mesh at this stage? If needing to replace th ...