Ensure that an element exists in Selenium before proceeding with actions

Currently, I am undergoing testing with the Selenium web driver and one of the requirements is to wait for my object to be defined on the page. Important: There are no visible changes in the DOM to indicate when my object is ready, and it's not feasible to alter that. Therefore, please refrain from suggesting such a modification as it is imperative for me to verify using the console.

Typically, after a page finishes loading, there is a waiting period ranging between 0-5 seconds until my object becomes accessible. The approach involves looping window.myObject !== undefined until this condition validates, at which point I can confidently execute myObject.myFunctionCall(). If I skip this waiting step and directly call myObject.myFunctionCall() post page load completion, there's a high probability of encountering an error stating myObject is not defined.

On manual execution via the browser console, these steps work flawlessly:

let ret = false;
while (ret === false) {
    ret = window.myObject !== undefined;
    console.log(ret);
}
// At this stage, ret holds true value indicating that myObject is defined and test continuation is feasible
myObject.myFunctionCall()
...

However, when attempting the same process with the selenium driver (this.driver) by implementing the following code:

let ret = null;
while (ret === null) {
    let val = this.driver.executeScript("window.myObject !== undefined;"); //returns promise
    console.log(val);
    ret = await val; //await promise resolution and assign value to ret
    console.log(val);
    console.log(ret);
    //Unexpectedly, 'ret' remains null regardless
}

This results in a continuous cycle of output leading up to test failure accompanied by

Error: function timed out, ensure the promise resolves within 30000 milliseconds
:

Promise { <pending> }
Promise { null }
null
Promise { <pending> }
Promise { null }
null
Promise { <pending> }
Promise { null }
null
...

What could I be overlooking here? Is there an alternative method within the Selenium web driver to determine if my object is defined?

Answer №1

The structure I ended up with looks something like this:

// Checking if myObject is defined
const checkObjectDefined = () => window.myObject !== undefined;

let ObjectExists = false;
while (ObjectExists !== true) {
    ObjectExists = await this.driver.executeScript(checkObjectDefined);
    await this.driver.sleep(50);
}

// Proceed with the test

But there's a catch - if I move the checkObjectDefined definition to another file and try to import it, I get an error saying

InvalidArgumentError: invalid argument: 'script' must be a string
.

Take a look at this issue:

I have a file called helpers/myObject_helper.js where I want to define the method, but when I attempt to use it in another file, I get the same error

InvalidArgumentError: invalid argument: 'script' must be a string
:

helpers/myObject_helper.js:

// Checking if myObject exists
const checkObjectDefined = () => window.myObject !== undefined;

testcases/myObject_testcase.js:

const ObjectHelper = require('helpers/myObject_helper.js');

let ObjectExists = false;
while (ObjectExists !== true) {
    ObjectExists = await this.driver.executeScript(ObjectHelper.checkObjectDefined);
    await this.driver.sleep(50);
}

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

Unable to retrieve nested object from an immutable object

How can I access an Array in an object? I want to display the entire list. render() { var elems = this.props.items.course_list; console.log(elems); return ( <div> </div> ) } Here is a visual representation: htt ...

Mastering Dropdown Navigation and Value Setting in Angular

I am facing a challenge with two components named ComponentA and ComponentB. In ComponentB, there is a link that, when clicked, should navigate to ComponentA and send specific data to it. This data needs to be displayed in the dropdown options of Component ...

Sending information to ajax request upon successful completion

I needed to transfer the output of the json_encode() function to jQuery. Once successful, I intended to refresh a specific division. Action: <a id="js-delete-file" href="#" data-url="<?php echo site_url('document_items/remove/'. $value[&a ...

Show image in ReactJS using flask send_file method

Using Flask's send_file function, I send an image to the client in the following way: @app.route('/get-cut-image',methods=["GET"]) def get_cut_img(): response = make_response(send_file(file_path,mimetype='image/png')) respon ...

"The issue with the Node.js object arises when it is not being used as a function

I am currently working on a node.js app and have created a module for it. The app also makes use of socket.io, and I want to pass the socket.io object into the auction object during creation. While this method works fine outside of Node, I encountered an ...

Can errors from model validation in ASP.NET MVC be stored and passed to a different method?

My task involves passing a group of models through a single view model to a controller. To achieve this, I utilized the html.beginform method and passed the group to a single method in the controller. The objective is to save this model data in a database. ...

Using jQuery's .post() method to automatically scroll to the top of

Is there a way to prevent the automatic scrolling to the top of the page when executing the buy function? Here is the code snippet involved: <a href="#" onClick="buy(id)">Buy</a> The buy function utilizes the $.post() function for processing t ...

What steps should I take to make sure that the types of React props are accurately assigned?

Dealing with large datasets in a component can be challenging, but I have found a solution by creating a Proxy wrapper around arrays for repeated operations such as sorting. I am looking to ensure that when the data prop is passed into my component as an ...

Make sure to include crossorigin="anonymous" in all img tags before the images start loading

I am currently facing issues with my canvas displaying errors due to cached images causing CORS policy errors. The solution I am considering is adding crossorigin="anonymous" to all the images on my website. However, I am unsure of how to impleme ...

Using Bootstrap Collapse with EJS Iteration

I am having trouble with this specific section of my ejs file where the collapse feature is not functioning correctly. Can someone please assist me? <% for(var i=0;i<data.length;i++){%> <div id="content"> <p><%=data[i].w ...

JavaScript Routing with Multiple Files

I tried to access api.js from Routes.js, but I encountered an issue stating that the function my_function_in_api is not defined. Here is my code, could you please help me identify where the problem lies: Routes.js var val = require('file name') ...

"Python Selenium: How to utilize innerHTML and implement wait functionality

I am facing an issue with waiting for the innerHTML element to load in my code. Here is a snippet of what I have tried: element = WebDriverWait(driver, 120).until(EC.presence_of_element_located((By.XPATH, XPATH))) element = element.get_attribute('inn ...

What is the best way to manage Page Refresh using Angular.js?

I recently followed the tutorial at http://scotch.io/bar-talk/setting-up-a-mean-stack-single-page-application This guide went over controllers and services using angular.js for a single-page application. However, when I try to directly access /pageName o ...

Having trouble getting my Python Selenium script to interact with dropdown options

I am currently utilizing a Selenium code in Spyder 3.8 with Anaconda. Everything runs smoothly when no options are added to the driver; it navigates to the URL and performs the necessary actions. However, adding options seems to pose an issue where the bro ...

Information vanishes on mobile devices

After creating a messaging app using React, TypeScript, and Firebase, everything works smoothly locally on both desktop and mobile. However, once the app is deployed, a problem arises specifically on mobile devices. The message input component ("sendMessa ...

Looking to create circular text using HTML, CSS, or JavaScript?

https://i.sstatic.net/pnu0R.png Is there a way to generate curved text in HTML5, CSS3, or JavaScript similar to the image linked above? I've experimented with transform: rotate(45deg); but that just rotates the text without curving it. Additionally, ...

Incorporating OpenRouteService into an Angular application on Stackbliz

I am encountering an issue with integrating OpenRouteService into my Stackblitz application. The component code is as follows: import { Component, OnInit } from '@angular/core'; import {Location} from '@angular/common'; import {Openro ...

Error: Trying to access the parent node of an undefined property

After incorporating this script into my webpage for the newsletter sign-up process, I aimed to reveal customized content post user subscription. <script> function insertAfter(referenceNode, newNode) { referenceNode.parentNode.insertBefore(newNode ...

Updated: "Adjust the preserveAspectRatio attribute in the SVG element within the Lottie player"

I have successfully incorporated a lottie json file using the lottie player. Unfortunately, I do not have access to the SVG file itself, only the json file. My goal is to modify the preserveaspectratio attribute of the SVG to xMinYMax meet instead of xMi ...

Removal of div elements based on checkbox being unchecked - a step-by-step guide

How can I delete elements from a div when the checkbox is unchecked? function removeCampaignName(id) { var campaignDisp = $('#camp' + id).html(); if ($("#campaign-name-disp").text().search("" + campaignDisp) === -1) { ...