Selenium – How to handle WAIT

if selenium script run faster than code which we want to test, it could happen that can’t find element. there are some ways to handle this problem depends on different cases

  • Sleep

This is the easiest but inefficient way. It mean wait fixed time , then try again. Usually we don’t use this way since it depends on the load time and it is not efficient.

public static void Wait(int miniseconds)
        {
            Thread.Sleep(miniseconds);
        }

 

  • WebDriverWait

This Method can resolve most of cases if there is no ajax load. Code wait until one element is present.

private static void WaitElement(By by, double seconds)
        {
            try
            {
               var wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(seconds))
                {
                    Message = @by.ToString() + " is not exist"
                };
                wait.Until((d) => d.FindElement(@by));
            }
            catch(Exception e)
            {
                GetScreenShot(e);
            }
        }
  • AjaxWait

Below method is generally assert that if ajax call finished.

        public static void WaitForAjaxCallFinish()
        {
            WaitForConditions("return window.jQuery.active == 0");
        }
        
        public static void WaitForConditions(string script)
        {
            var wait = new DefaultWait<bool>(((bool)((IJavaScriptExecutor)Driver).ExecuteScript(script) == true))
            {
                Timeout = TimeSpan.FromSeconds(_stepTimeout)
            };
        }
  • But no jquery connection doesn’t mean expected element is present. so the below method is the way to finnaly resolve wait problem.
// try to find element every 5 seconds, until element is exist or it's time out.
        public static IWebElement GetElementUntilPresent(By by)
        {
            for (int i = 0; i < _stepTimeout; i = i + 5)
            {
                try
                {
                   return Driver.FindElement(by);
                }
                catch (Exception e)
                {
                        Wait(5000);
                }
            }
            return null;
        }
  • Sometimes we get test case fail with below message

The HTTP request to the remote WebDriver server for URL http://localhost:13915/session/01ab4ef8075bba3d64e8fc3062aa79b5/element timed out after 60 seconds.

I try : 1. set page time out

private static void OpenBrowser(string pageTitle)
{
Driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromMinutes(_pagetimeout));
Driver.Manage().Timeouts().SetScriptTimeout(TimeSpan.FromMinutes(_pagetimeout));
Driver.Navigate().GoToUrl(WebsiteUrl);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值