Facing challenges when running asynchronous mocha tests using async/await syntax

Working on E2E tests using mocha and selenium-webdriver has been quite a challenge for me. Although I have implemented async/await functions to handle most of the tests smoothly, I am facing an issue where none of the tests are completing successfully. Here is a snippet of my current code:

describe('Some test', function () {
  before(function () {
    driver.navigate().to('http://localhost:3000')
  })

  after(function () {
    driver.quit()
  })

  it('should display element', async function () {
    let elementFound = false
    try {
      await driver.wait(until.elementIsVisible(driver.findElement(By.className('element'))), 1000)
      assessForm = await driver.findElement(By.className('element')).isDisplayed()
      assert.ok(elementFound)
      console.log('elementFound', elementFound)
    } catch (err) {
      console.log(err)
      assert.fail(err)
    }
  })
})

The main problem appears to be that the after function gets executed before the test can complete properly. The error logs indicate:

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

{ NoSuchSessionError: no such session (Driver info: chromedriver=2.36.540469 (1881fd7f8641508feb5166b7cae561d87723cfa8),platform=Mac OS X 10.13.3 x86_64) at Object.checkLegacyResponse (/Users/me./myproject/node_modules/selenium-webdriver/lib/error.js:585:15) at parseHttpResponse (/Users/me./myproject/node_modules/selenium-webdriver/lib/http.js:533:13) at Executor.execute (/Users/me./myproject/node_modules/selenium-webdriver/lib/http.js:468:26) at at process._tickCallback (internal/process/next_tick.js:188:7) name: 'NoSuchSessionError', remoteStacktrace: '' }

Even without the after() function, the timeout error persists,

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

but, interestingly, my console.log confirms that the element was found.

Trying to make after() async as well:

  after(async function () {
    await driver.quit()
  })

resulted in encountering the same initial error.

It's worth mentioning that I've come across sources claiming not needing to use done() with async/await, yet the errors persist regardless. How do I resolve this situation? Everything seems to be set up correctly, but the tests just won't run smoothly without interfering with each other.

Answer №1

If you want to avoid using:

await driver.wait(until.elementIsVisible(driver.findElement(By.className('element'))), 1000)

You can experiment with:

await driver.wait(until.elementLocated(By.className('element'))).isDisplayed()

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

How to choose a value from an auto complete dropdown using Selenium?

<div class="cityLocaDiv1 col-lg-12 col-md-12 col-sm-12 col-xs-12"> <input class="form-control" id="city-locality1" placeholder="Enter City or Locality" type="text"> <span class="glyphicon glyphicon-chevron-down cityicon1" style="positi ...

Tips for executing an asynchronous function in a synchronized manner within a Node.js environment

Currently, I am utilizing the Express framework. The issue that I am encountering involves a variable called 'duration'. Whenever a request is made to '/', the total duration of a given video is calculated and saved to this variable. H ...

Identifying Button Clicks with Selenium and C# WebDriver

Currently, I am utilizing selenium with IE for automating web testing. On my webpage, a form gets filled out and then a button is clicked using the following code: driver.FindElement(By.CssSelector("td.ne-fieldvalues > input[type=\"button\"]" ...

Trouble with clicking the button in Selenium Webdriver? Element located but unable to be clicked

Can anyone assist me in finding a solution to my current problem? I have dedicated a significant portion of today trying various solutions both on this platform and through Google. To get straight to the point, I am facing an issue with Selenium automatio ...

Issue with API showing return value as a single value instead of an array

My database consists of collections for Teachers and Classes. In order to fully understand my issue, it's important to grasp the structure of my database: const TeacherSchema = new Schema( { name: { type: String, required: true } ...

What is the process for setting up geckodriver to have a trace log level using firefox_options?

When attempting to execute selenium on a VPS for running tests in Python, I encountered an issue. Here's the Python code snippet: from selenium import webdriver from selenium.webdriver.firefox.options import Options options = Options() options.log.l ...

Load jQuery core asynchronously with a backup plan

Exploring performance optimization and non-blocking scripts in the header, my focus has been on asynchronously loading jQuery itself. In my search, I came across a jQuery Loader script that can async load jQuery and then handle and queue jQuery document r ...

Guide on choosing a checkbox within a multiple select box using Selenium WebDriver in Java

I have the following code snippet for a multiple select box on a webpage, and I am looking to automate the selection of an option group using Selenium WebDriver. <div class="ms-drop bottom" style="display: block;"> <div class="ms-sear ...

Facing difficulty with Sharepoint pop-up page while using Selenium Webdriver

Struggling to automate a Sharepoint site with Selenium Webdriver, as my code can't seem to locate elements on a new popup that appears. The scenario is this: in the script, there's a link leading to a new noticeboard item. When clicked, it trigg ...

Encountering an issue when trying to choose the start date

When attempting to select the From-Date on "opensource-demo.orangehrmlive.com" Dashboard > Apply leave, I encountered an issue where I was unable to click on the from-date textbox. driver.findElement(By.id("applyleave_txtFromDate").click(); Select secMon ...

Troubleshooting Negative Numbers in Python Regular Expressions

Currently, I am utilizing Python and RobotFramework for my testing purposes. Throughout my tests, I manipulate numbers in string format (such as $486,100, -23,000) and convert them to integers in order to compare them. Transforming positive numbers is no ...

A guide on utilizing WebDriverWait in Selenium to retrieve the value of the "style" attribute from an element

There is a specific time when the style changes to "display: block". I need to wait for this change before continuing. <div class="dialog transportxs pre_render" id="dialog_transport" style="z-index: 3; display: block;"> ...

What is the best way to execute multiple test cases using Selenium with Python?

import unittest from selenium import webdriver from datetime import datetime class Index(unittest.TestCase): @classmethod def setUpClass(cls): chrome_options = webdriver.ChromeOptions() prefs = {"profile.default_content_setting_values.notificat ...

Struggling to use XPath to interact with a pop-up window in Selenium

Is there a way to retrieve 'CIK' codes from the 'SEC' using Selenium? When I try running the code, a "survey" pop-up appears that doesn't show up when doing it manually. This causes issues with my code because I can't inspect ...

When there is an expensive calculation following a Vue virtual DOM update, the update may not be

Currently, I am facing an issue with adding a loading screen to my app during some heavy data hashing and deciphering processes that take around 2-3 seconds to complete. Interestingly, when I removed the resource-intensive parts, the screen loads immediate ...

Utilizing Selenium with C# to effectively target elements by their "nobr" attribute

I'm working with this HTML code: <nobr class="ms-crm-Form-Title-Data autoellipsis"> Text - Some Text My goal is to retrieve the text value using a Selenium driver. I've attempted to do so with a CssSelector: [FindsBy(How = How.Css ...

Encountered an obstacle while running some Java code using Selenium

To begin, you will need to import the following two packages: org.openqa.selenium.*- includes the WebDriver class required to create a new browser with a specific driver org.openqa.selenium.firefox.FirefoxDriver - includes the FirefoxDriver class needed t ...

Is it possible to extract the value in JavaScript, add it, and then return the result after a for loop in Cypress automation?

checkActiveInterfaces() { var totalSum = 0; var counter; for (counter = 1; counter <= 5; counter++) { cy.xpath(`(//*[name()='g' and @class ='highcharts-label highcharts-data-label highcharts-data-label- ...

Using Java's get() and getAttribute(), replace Selenium in C# for enhanced automation

Embarking on automation tasks in Selenium using Java, but now venturing into C# with selenium. Seeking guidance on how to translate the following Java logic into C# Visual Studio: Int count = driver.findelements(By.Name("radiobutton")).size(); For(int ...

Unable to physically tap on the checkbox input, though able to perceive the value it holds

When running my protractor test, I encountered an issue with the following statement: await element(by.model('publishCtrl.isPublishedInAllRegions')).click(); The test failed and returned an error message stating "ElementNotVisibleError: element ...