App & Browser Testing Made Easy

Give your users a seamless experience by testing on 3000+ real devices and browsers. Don't compromise with emulators and simulators

Home Guide Wait Commands in Selenium C and C#

Wait Commands in Selenium C and C#

By Mohit Joshi, Community Contributor -

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#

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();

     }

    }

}

Explicit Wait Command in C#

In the Implicit Wait command, it waits for a specific period. However, in Explicit Wait, it 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. This is the reason it 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.

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()

To know further methods, you may refer to the Selenium official documentation.

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();
  

     }


    } 

}

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

 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#

The Fluent Wait command in Selenium 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();

   

     }

 

    }

}

However, the syntax for ignoring exceptions while using Fluent Wait is as follows:

fluentWait.IgnoreExceptionTypes(typeof(ElementNotSelectableException));

Summing it Up

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 3000+ 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

Try Selenium Testing on Cloud

Tags
Automation Frameworks Automation Testing

Featured Articles

Top C# Testing Frameworks for every Developer

Selenium Commands every Developer or Tester must know

Curated for all your Testing Needs

Actionable Insights, Tips, & Tutorials delivered in your Inbox
By subscribing , you agree to our Privacy Policy.
thank you illustration

Thank you for Subscribing!

Expect a curated list of guides shortly.