Selenium with C Sharp - How to perform Explicit Wait method?

SeleniumAutomation TestingTesting Tools

We can perform explicit wait with Selenium webdriver in C#. This is done to achieve synchronization between our tests and the elements on the page. For implementation of explicit wait, we have to take the help of the WebDriverWait and ExpectedCondition classes.

We shall create an object of the WebDriverWait class. The webdriver waits tillspecified wait time waiting for the expected condition for an element is satisfied.

After the time has elapsed, an exception is raised by Selenium.

The explicit waits are dynamic in nature which means if we have an explicit wait of five seconds and the expected condition is met at the third second, then the webdriver shall move to the next step immediately. It does not wait till the entirefive seconds.

Some of the expected conditions are −

  • UrlToBe

  • VisibilityOfAllElementsLocatedBy

  • UrlContains

  • AlertIsPresent

  • AlertState

  • ElementToBeSelected

  • ElementIsVisible

  • ElementExists

  • ElementSelectionStateToBe

  • ElementToBeClickable

  • InvisibilityOfElementWithText

  • InvisibilityOfElementLocated

  • TextToBePresentInElementLocated

  • TextToBePresentInElementValue

  • TextToBePresentInElement

  • StalenessOf

  • TitleContains

  • FrameToBeAvailableAndSwitchToIt

  • PresenceOfAllElementsLocatedBy

  • TitleIs

Syntax

WebDriverWait w =
new WebDriverWait(driver, TimeSpan.FromSeconds(20));
w.Until(ExpectedConditions.ElementIsVisible(By.TagName("h1")));

Let us try to wait for the text - Team @ Tutorials Point to be visible on the page −

Example

using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
namespace NUnitTestProject2{
   public class Tests{
      String url = "https://www.tutorialspoint.com/about/about_careers.htm";
      IWebDriver driver;
      [SetUp]
      public void Setup(){
         //creating object of FirefoxDriver
         driver = new FirefoxDriver("");
      }
      [Test]
      public void Test2(){
         //URL launch
         driver.Navigate().GoToUrl(url);
         //identify element then click
         IWebElement t = driver.FindElement(By.XPath("//*[text()='Team']"));
         t.Click();
         //expected condition of Element visibility
         WebDriverWait w = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
         w.Until
         (ExpectedConditions.ElementIsVisible(By.TagName("h1")));
         //identify element then obtain text
         IWebElement n = driver.FindElement(By.TagName("h1"));
         Console.WriteLine("Text is: " + n.Text);
      }
      [TearDown]
      public void close_Browser(){
         driver.Quit();
      }
   }
}

Output

raja
Published on 07-Apr-2021 08:49:59
Advertisements