Wait Commands in Selenium C# : Implicit, Explicit & Fluent Waits
By Mohit Joshi, Community Contributor - November 27, 2024
A widely used open-source framework for automated testing is Selenium, which ensures that web applications run properly across all browsers and operating systems. As a result, Selenium has become very popular in the testing industry.
To test our web applications better and resolve all challenges we face, it is important to learn certain Selenium best practices while writing the test code. One of the most important factors in Selenium C# is the ability to use Wait commands to reduce the flakiness of tests.
Let’s see how wait commands in Selenium C and C# help us resolve time-lag issues in our web applications.
What is Wait Commands in Selenium?
Selenium wait commands are used in test automation to handle the dynamic loading of web elements. Since some elements might have been created with the help of ajax or front-end frameworks, it takes some time for them to load, but since they haven’t been loaded yet, running tests on them fails.
Selenium wait commands pause the test execution for a certain amount of time until those elements are ready in the DOM. As a result, our Selenium tests are more reliable.
Types of Wait Commands in Selenium
The Selenium framework offers three types of wait commands for implementation.
Implicit Wait Command in C#
In Selenium C#, Implicit Wait is used to instruct the WebDriver to wait for a certain amount of time before throwing an exception if it cannot find an element. This wait is applied globally for all elements, meaning the WebDriver will repeatedly check for the presence of an element in the DOM during the specified time period before proceeding with the next step.
Implicit wait pauses the execution of the web driver for a specified period before throwing any error. The specified time is based upon the time required by the web elements to get ready for the test, and hence get loaded on the page. However, the execution time of the overall test increases.
If the particular element takes more time than what is specified, the Selenium web driver throws an error “NoSuchElementException“.
The syntax for using the Implicit wait command in Selenium C# is as follows.
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(Value);
Let’s understand how to use implicit wait with the help of an example. In this example, we will navigate to Google’s homepage and will wait there for 20 seconds before performing the next step of our test. Moreover, this will also increase the execution time by 20 seconds.
using System; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; namespace Test { class Program { Public static void Main(string[] args) { //Initialising ChromeDriver IWebDriver driver = new ChromeDriver(); //Navigating to Google's homepage driver.Navigate().GoToUrl(" https://www.google.com "); //Applying Implicit Wait command for 20 seconds driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20); //Clicking on an element after waiting for 20 seconds driver.FindElement(By.LinkText("I'm Feeling Lucky")).Click(); } } }
When to Use Implicit Wait
- For general waiting when you are unsure about the load time of elements.
- For static pages where elements are mostly available without too much delay.
- When you want a simple, global wait configuration for all element searches.
When Not to Use Implicit Wait
- When dealing with dynamic web pages or AJAX calls where elements might load at different intervals.
- When precise control over waiting times is needed, such as waiting for specific conditions like, element visibility, Explicit Wait is preferred.
Explicit Wait Command in C#
In Selenium C#, an Explicit Wait is used to wait for a certain condition to occur before proceeding with further actions. Unlike Implicit Wait, which is applied globally, Explicit Wait is more targeted and allows you to wait for specific conditions to be met, such as an element becoming visible, clickable, or present.
Implicit Wait command, in Selenium C# waits for a specific period. However, Explicit Wait in Selenium C# will wait till certain conditions occur. The wait here for a web element is not for a specific period but till the web element is ready in the DOM for testing. Explicit Wait C# is also known as “smart wait“.
The Explicit Wait command checks the condition (element to become clickable, displayed, etc) every 250ms. Moreover, Implicit wait is only applicable with FindElement methods, however, Explicit Wait has several possible conditions.
The Selenium Webdriver provides two classes for the implementation of Explicit Wait.
- WebDriverWait
- ExpectedConditions
The WebDriverWait calls the ExpectedConditions class method until it returns successfully or the specified time is over. It is a major improvement for Implicit Wait, as there is no extra delay in the test.
The syntax for the usage of Explicit Wait is as follows
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); wait.Until(ExpectedConditions.ElementExists(By.Id("id")));
In the above syntax, ElementExists() is used as a method, for example, however, ExpectedConditions class can contain several other methods also. Some of the common methods used are.
- AlertIsPresent()
- ElementIsVisible()
- ElementExists()
- ElementToBeClickable(By)
- ElementToBeClickable(IWebElement)
- ElementToBeSelected(By)
- TitleContains()
- UrlMatches()
- TextToBePresentInElementValue(IWebElement, String)
- TextToBePresentInElement()
Also-Read: How to use Wait commands in Selenium WebDriver
Now, let’s understand how to use the Explicit wait command in Selenium C# with the help of an example.
To use Explicit wait in your code, first install the following packages into your script.
- OpenQA.Selenium.Support.UI – It will help in executing the WebDriverWait class
- SeleniumExtras.WaitHelpers – It will help execute ExpectedConditions class and its methods into our test script.
In this test, the test will navigate to the Gmail website, will fill up login details, and after signing in, we shall wait for the compose button to get loaded, and once it is loaded, the button will be clicked. After clicking the button, we shall wait for 20 seconds with the help of Implicit Wait, and then will close the browser.
using System; using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Support.UI; using SeleniumExtras.WaitHelpers; using System; namespace ExplicitWait { class ExplicitWait { IWebDriver driver; [SetUp] public void open_gmail() { driver = new ChromeDriver(); driver.Manage().Window.Maximize(); } [Test] public void login_and_wait() { String email_site = "https://gmail.com"; driver.Url = email_site; IWebElement Email = driver.FindElement(By.Id("Email")); Email.SendKeys("your_username"); Email.SendKeys(Keys.Return); IWebElement Password = driver.FindElement(By.Id("Email")); Password.SendKeys("your_password"); Password.SendKeys(Keys.Return); driver.FindElement(By.Id("signIn")).Click(); String xpath = "//div[contains(text(),'COMPOSE')]"; WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); IWebElement ComposeButton = wait.Until(ExpectedConditions.ElementExists(By.XPath(xpath))); ComposeButton.Click(); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30); } [TearDown] public void close_Browser() { driver.Quit(); } } }
When to Use Explicit Wait in Selenium C#
- Waiting for specific conditions: When you need to wait for elements to become visible, clickable, or meet other conditions.
- Dynamic content: For pages where elements load asynchronously (e.g., AJAX, JavaScript).
- Avoiding stale elements: When you need to ensure an element is present before interacting with it.
- Waiting for page transitions: When the page content changes dynamically (e.g., after form submission or navigation).
- Optimized test stability: To handle scenarios where delays are unpredictable or elements are hidden for some time.
When Not to Use Explicit Wait in Selenium C#
- Static content: When elements are always available and don’t change dynamically.
- Short test cases: For simple interactions where elements are readily available, using explicit waits may slow down tests unnecessarily.
- Global waits: When the same waiting condition applies to all elements, an implicit wait may be more efficient.
- Overusing waits: When using explicit waits on every element unnecessarily leads to bloated code and slower tests.
- Simple element retrieval: For immediate access to elements when no delay is expected like, during initialization or setup.
There are a few exceptional situations occurs, which happen while the driver searches for the web element in the DOM. However, if you want to ignore these errors while waiting for some condition to occur, IgnoreExceptionTypes() method is used. A few such error situations are as follows.
- NoSuchElementException
- StateElementReferenceException
- ElementNotVisibleException
- ElementNotSelectableException
- NoSuchFrameException
Read More: Exception Handling in Selenium WebDriver
The syntax while using Explicit Wait is as follows:
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); wait.IgnoreExceptionTypes(typeof(ElementNotSelectableException));
Fluent Wait Command in C#
In Selenium C#, Fluent Wait is a more flexible version of explicit wait that allows you to define not only the maximum wait time but also the frequency with which the condition should be checked. It provides greater control, such as the ability to ignore specific exceptions such as., NoSuchElementException during the wait period.
Fluent Wait command in Selenium C# is similar to Explicit Wait in so many aspects. It allows you to control the Web Driver to set the specified time for some condition to appear before it could throw the error “ElementNotVisibleException”.
The main advantage of implementing the Fluent Wait command is setting the polling frequency. Polling frequency is the frequency at which the driver checks for the element whether it has loaded or not. It has the attribute .pollingfrquency, and its default value is 500ms, which means the driver will check every 500 milliseconds before throwing the error.
The syntax for the usage of Fluent Wait is as follows:
DefaultWait<IWebDriver> fluentWait = new DefaultWait<IWebDriver>(driver); fluentWait.Timeout = TimeSpan.FromSeconds(5); fluentWait.PollingInterval = TimeSpan.FromMilliseconds(polling_interval_in_ms);
Let’s understand Fluent Wait with the help of an example, demonstrating the previous example where the driver waits for the compose button to appear in Gmail. In this example, there is a wait of 5 seconds and a polling frequency of 250ms.
using System; using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Support.UI; using SeleniumExtras.WaitHelpers; using System; namespace Selenium_ExplicitWait_Demo { class Selenium_ExplicitWait_Demo { IWebDriver driver; [SetUp] public void open_gmail() { driver = new ChromeDriver(); driver.Manage().Window.Maximize(); } [Test] public void login_and_wait() { DefaultWait<IWebDriver> fluentWait = new DefaultWait<IWebDriver>(driver); fluentWait.Timeout = TimeSpan.FromSeconds(5); fluentWait.PollingInterval = TimeSpan.FromMilliseconds(250); String email_site = "https://gmail.com"; driver.Url = email_site; IWebElement Email = driver.FindElement(By.Id("Email")); Email.SendKeys("your_username"); Email.SendKeys(Keys.Return); IWebElement Password = driver.FindElement(By.Id("Email")); Password.SendKeys("your_password"); Password.SendKeys(Keys.Return); driver.FindElement(By.Id("signIn")).Click(); String xpath = "//div[contains(text(),'COMPOSE')]"; IWebElement ComposeButton = fluentWait.Until(dom => dom.FindElement(By.XPath(xpath))); ComposeButton.Click(); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30); } [TearDown] public void close_Browser() { driver.Quit(); } } }
When to Use Fluent Wait in Selenium C#:
- Need for polling control: When you want to check for an element at specific intervals (such as, every 500 milliseconds).
- Handling dynamic content: For pages where elements may appear intermittently or after varying delays.
- Ignoring specific exceptions: When you need to ignore exceptions like NoSuchElementException during the wait.
- Long wait times with frequent checks: When the expected condition takes time, but you want to avoid continuously checking without delay.
- Complex wait scenarios: When you need greater flexibility in waiting for multiple conditions or types of exceptions.
When Not to Use Fluent Wait in Selenium C#
- Simple scenarios: When elements are expected to be available immediately or within a short, predictable time.
- Performance-sensitive cases: When excessive polling and delays may negatively impact test execution speed.
- Global waits: When the same wait condition applies to all elements (in such cases, ImplicitWait is more efficient).
- No dynamic content: When the page is static and all elements are readily available with no delay.
- Frequent short waits: When there’s no need to check repeatedly for a condition, and a one-time explicit wait suffices.
However, the syntax for ignoring exceptions while using Fluent Wait is as follows:
fluentWait.IgnoreExceptionTypes(typeof(ElementNotSelectableException));
Why use BrowserStack Automate for Selenium C# Tests?
Here’s why you should use BrowserStack Automate to run Selenium C# Tests:
- Parallel Testing: BrowserStack Automate allows you to run tests simultaneously on various devices and browsers, reducing execution time and providing faster feedback.
- Real Devices and Browsers: Testing on actual devices and browsers gives a true picture of your app’s performance, unlike emulators. You can access the latest devices without needing to purchase them.
- Dedicated Dashboard: Automate provides a dashboard to monitor and manage your tests. It displays test results (Pass/Fail/Pending), device and browser details, test duration, screenshots, and more.
- Custom Reports with Artifacts: Create detailed and customizable reports that include test results, device and browser configurations, video recordings, and screenshots.
- Seamless CI/CD Integration: Easily integrate with CI/CD tools like Jenkins, TeamCity, and TravisCI, ensuring faster and more reliable application delivery.
Conclusion
In this tutorial, we understood how some web elements could take more time to load than others. This happens when the web elements are built using Ajax or any front-end framework. However, this causes hindrance in our testing, and thus, we don’t get a flawless testing experience.
Therefore, Wait commands play an important role in Selenium automation testing to resolve this as it pauses the test until we get the specific ready for testing in the DOM; however, it also increases the time of execution of our tests.
BrowserStack’s Selenium grid offers 3500+ real devices and browsers for automated testing. Users can run tests on multiple real devices and browsers by simply signing up, logging in, and selecting the required combinations