Synchronization in Selenium is the process of matching the execution speed of the test script with the loading speed of the application under test . Synchronization prevents errors such as NoSuchElementException .
How to achieve synchronization in the Selenium WebDriver ?
Synchronization in selenium is very important to ensure the alignment between browser driver and browsers when performing variety of task with web elements that might load at different different intervals . There are multiple methods to achieve synchronization.
Types Of Synchronization in Selenium
- Thread.Sleep
- Explicit Waits
- Implicit Wait
- Fluent Wait
- Thread.Sleep:
In Java Thread.sleep() function temporarily pause the current thread’s execution for a specified duration in milliseconds . One can’t use negative value as an argument for milliseconds.
Thread.sleep(5000);//sleep for 5 sec
Thread.sleep() function is not time efficient . Let’s understand this with an example, Let in a page Thread.sleep(7000); But page load in 3 sec only, but it will pause for 4 sec unneccesarily to make it 7sec, due to which it can’t be consider as time efficient .
2. Explicit Waits :
Explicit wait is more flexible as it enable us to pause test execution until a particular condition is satisfied . If the condition isn’t met within the designated timeframe , an exception will occur . Unlike implicit waits , which apply globally to all elements , explicit waits are applied to a specific element and specific state.
Explicit wait is more flexible to use as it is dynamic in nature i.e. if the condition is met before the maximum timeout( e.g. When the limit is 9sec, condition met in 2 sec only ), Selenium continues immediately without waiting for 9 sec.
Some of the expected conditions that can be used in Selenium explicit wait are :
- alertIsPresent()
- elementToBeClickable()
- elementToBeSelected()
- titles()
- titleContains()
- visibilityOf()
- visiblityOfElementLocated()
- presenceOfElementLocated()
Syntax of Explicit Wait :
Example:
WebDriver wait= new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.visiblityOfElementLocated(By.xpath(”your xpath here “)));
3.Implicit Wait : Implicit wait is a wait which directs the selenium webdriver to wait for a certain time before throwing an exception . Once this time is set , Webdriver will wait for the element before throwing NoSuchElement Exception . Implicit wait is a global wait and it is applied to all the elements on the webpage .
Syntax:
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
4.Fluent Wait :
Fluent Wait in Selenium sets the maximum duration for the Selenium WebDriver to wait until a specific condition becomes visible . It also specifies how often WebDriver will check for the condition before raising an ‘ElementNotVisibleException’.
