Steps for verifying the presence of an element in Selenium using JavaScript

I'm facing an issue with a Jest and Selenium test. I'm trying to verify if an element is removed from the DOM after being clicked.

Here's what I've attempted:

 test('User removes button after clicking on it', async (done) => {
    await driver.navigate().to('myProjectUrl');
    await driver.wait(until.elementLocated(By.css('.wrapper')), 10000);
    await driver.findElement(By.id('buttonId')).click();
    const deleteButton = await driver.findElement(By.id('buttonId'));
    expect(deleteButton.isDisplayed()).not.toEqual(true);
    done();
});

While this appears to be successful and the test passes, I'm encountering the following error message:

StaleElementReferenceError: stale element reference: element is not attached to the page document

I also tried a different approach:

test('User removes button after clicking on it', async (done) => {
    await driver.navigate().to('myProjectUrl');
    await driver.wait(until.elementLocated(By.css('.wrapper')), 10000);
    await driver.findElement(By.id('buttonId')).click();
    const buttonOrMessage = await driver.wait(until.elementLocated(By.id('buttonId)), 300, 'missing_button');
    expect(buttonOrMessage).toEqual('missing_button');
    done();
});

However, this method is giving me an error instead of the expected message.

If you have any suggestions or insights on what might be missing in my approach, your assistance would be greatly appreciated.

Answer №1

Once the element deleteButton has been removed, it is no longer accessible or visible. This will cause .isDisplayed() to throw a StaleElementReferenceError, which is an expected behavior in this scenario.

To handle this situation, you can implement a try / catch block to re-search for the id 'buttonId' and base your assertion on that result.

For example:

let buttonIsStillThere;
try {
    buttonIsStillThere = driver.findElement(By.id('buttonId')).isDisplayed();
} catch () {
    buttonIsStillThere = false;
}

Answer №2

Utilize the until.stalenessOf function to pause until the button is no longer in the HTML structure:

test('Button disappears after being clicked', async (done) => {
  await driver.navigate().to('myProjectUrl');
  let removeBtn = await driver.wait(until.elementLocated(By.css('.wrapper #buttonId')), 10000);
  await removeBtn.click();
  await driver.wait(until.stalenessOf(removeBtn), 300, 'button still visible on the page');
  done();
});

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

Transforming complex mathematical equations into executable code using the node.js platform

Looking to implement a mathematical formula found at the following link: https://en.wikipedia.org/wiki/Necklace_(combinatorics)#Number_of_bracelets into node.js for calculating the total number of distinct ring sequences that can be created with n length ...

Insert an element into a JSON collection

I am currently working on a JavaScript function that utilizes an ajax call to retrieve data from an API in the form of a JSON array. Here is a snippet of the array structure that I receive: [ { "ErrorType": "Errors", "Explanations": [ { ...

Selenium encounters difficulties in extracting data from a table

I am having trouble extracting data from the table located at . The code snippet I am using seems to be unable to access it for some reason. Can anyone suggest why the table scraping is not working? from bs4 import BeautifulSoup from selenium import webd ...

Transferring identification data between views within an application (AngularJS, NodeJs, HTML)

I'm working on an HTML page that lists users from MongoDB. The page allows for deleting and updating users. I am encountering an issue with the update button - I want a new HTML page to appear with a form when the button is clicked, capturing the user ...

The styling of a CSS class in Internet Explorer may not be applied correctly if there are multiple elements sharing the same class name

For nearly a full week now, I've been plagued by a persistent issue! Here's the situation: I have 6 step tabs - step 1, step 2, and so on. Each tab has a CSS class called "locked" and "active." "Locked" - this style features top: 3em;, causing ...

Embedding image URLs fetched from JSON data within <li> elements

I have successfully retrieved a JSON response, which is displayed using the code below: Within my HTML document, I have the following structure: <ol id="selectable"></ol> In my JavaScript code, I make use of the following: <script type=" ...

Using the react-form library to create nested components with react.cloneElement

There is an issue that needs fixing with the library called react-form. Here is the error message I am currently facing: Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) ...

Encoding and Displaying Characters in HTML with UTF-8

I am experiencing an issue with UTF-8 characters in the page title. I would like to include the music symbol ♫ on the page title. The strange thing is that sometimes it displays correctly (in Google Chrome) and other times it shows a square symbol indic ...

Why isn't the field I added to my state functioning properly?

Can anyone explain why I am getting names without the added selected field??? I can fetch names from my API JSON (1) and I'm attempting to modify it by adding the selected field (2). export default function Display() { ... const init ...

The error message "Unexpected style type encountered while loading model in ifc.js" was displayed

When I try to load IFC files using the ifc.js library, I frequently encounter numerous messages like the following in the console: Unexpected style type: 3800577675 at 213152 (web-ifc-api.js: 933) Unexpected style type: 3800577675 at 213511 (web-ifc-api.js ...

Distinguish between a function and a constructor during execution

As I work with TypeScript, I am creating a function that accepts an error factory as an argument. This factory can be either a class name or a function. The function looks something like this: // Alias from class-transformer package type ClassConstructor& ...

Is there a way to dynamically modify the email content with the Gmail API using JavaScript?

I have received the message body and now I need to make some updates to it. When I try using this login/code, I encounter a 400 error. I believe the issue lies in the body parameter of the request. Can someone please assist me with this? var token = loca ...

Dropdown Menu with Bootstrap 4 Toggle Checkbox

Within a Bootstrap 4 dropdown menu, I integrated a checkbox styled with the Bootstrap Toggle Plugin. However, upon clicking the toggle switch, the menu abruptly closes. To address this issue, I added onclick="event.stopPropagation();" to the menu item, as ...

Complete the loop of ajax calls array instead of terminating when an error occurs in one of the calls

I am attempting to create a loop of ajax calls from an array and save each data result to be printed once all calls have been successfully received. The issue arises when any ajax call returns an error, causing the entire process to be aborted and the cal ...

Continual dark mode throughout page navigation with the ability to switch between light and dark modes

I've been experimenting with creating a persistent dark mode feature for web pages. My goal is to remember the user's preference as they navigate between pages. Additionally, I included a toggle button for switching between dark and light modes t ...

Creating a Slider with a Multitude of Images

I am working on a project to develop a gallery that pulls images from a JSON source. I have successfully implemented infinite scrolling to display the images on the first page. However, I am now facing a challenge when it comes to showing the selected imag ...

What is the best approach for locating and interacting with a button in Selenium WebDriver that lacks an id and title, but has a hover state?

Seeking guidance on how to locate and click on a button without a title? <div class="ui-fileupload-buttonbar ui-widget-header ui-corner-top"> <span class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-left ui-fileupload ...

I'm encountering inexplicable duplications of elements on my Wordpress site

Here is an example of my template header: <header> <?php if ( function_exists( 'jetpack_the_site_logo' ) ) jetpack_the_site_logo(); ?> <a class="menu-toggle">menu</div> <?php wp_nav_menu( array('them ...

Tips for automatically incorporating animation upon page initialization

I'm looking to add an automatic image effect when the page is loaded. I currently have this code in my js file: $(window).ready(function(){ $(pin).click(function(){ $("#pin01").show().animate({left: '650px'}); }) }); Here is the HTML wit ...

Node.Js Web Scraping: How to Extract Data from JavaScript-Rendered Pages Using Request

I am looking to extract specific content from Google search results that is only visible in browsers, potentially due to Javascript being enabled. Specifically, I am interested in scraping the Knowledge Graph "People also search for" information. Currentl ...