Search code examples
c#seleniumselenium-webdriverwebdriverwait

Can I reuse WebDriverWait in multiple sequential waits?


Given I need wait for one textbox appears, do something, and later I will need wait another Textbox. I want to know if this code is correct:

var waitForTextBox = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
waitForTextBox.Until(ExpectedConditions.ElementIsVisible(By.Id("txtFirstName"))).SendKeys("John");
waitForTextBox.Until(ExpectedConditions.ElementIsVisible(By.Id("txtLastName"))).SendKeys("Skeet");

or if instead of reusing waitForTextBox, I will need do like this:

var waitForFirstName = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
waitForFirstName.Until(ExpectedConditions.ElementIsVisible(By.Id("txtFirstName"))).SendKeys("John");

var waitForLastName = new WebDriverWait(driver, TimeSpan.FromSeconds(30));              
waitForLastName.Until(ExpectedConditions.ElementIsVisible(By.Id("txtLastName"))).SendKeys("Skeet");

Solution

  • Reusing the WebDriverWait objects for multiple "waits" is best. The only time you need a different WebDriverWait object is if you need two different timeout periods. Otherwise the only state that a WebDriverWait keeps is the driver, how long it waits, and a list of exception types that should be ignored.