My current task involves interacting with a website built in React using Selenium to choose a value from a dropdown menu.
Given that the website is built in React, I understand that waiting for the DOM to be ready may not always work as expected, but I still incorporate this step in my process.
Here are the lines of code that I have written and verified to be functional:
- The first three lines are used to click on the dropdown menu.
- The last three lines are used to select an item from the dropdown list.
/** Find dropdown and click on it */
await driver.wait(until.elementLocated(By.css('div#discipline')))
const dropdown = await driver.findElement(By.css('div#discipline'))
await dropdown.click()
/** Wait for the list, find the element to select, and click on it */
const dropOpts = await driver.wait(until.elementLocated(By.css('div#menu-discipline > div > ul')))
await driver.wait(until.elementLocated(By.xpath('//li[contains(text(),"Infirmary")]'))
const choice = await dropOpts.findElement(By.xpath('//li[contains(text(),"Infirmary")]'))
await choice.click()
- My first question pertains to the correctness of the above code. Although it executes successfully, I am unsure if it is truly correct.
- Secondly, I am questioning whether it is appropriate to FIRST wait for an element and THEN look for it, or vice versa.
- Finally, my most pressing concern lies with the last three lines of code. Is it best practice to A) wait for the parent element of the dropdown menu, B) wait for the dropdown menu itself to appear using
driver.wait
, C) locate the element I wish to select usingfindElement
? Or should I reverse the order?
I'm feeling a bit confused about this aspect and would appreciate some clarity.