Selenium: How to make the web driver to wait for page to refresh before executing another test

后端 未结 3 646
孤独总比滥情好
孤独总比滥情好 2020-12-13 00:50

I am writing Test Cases using Selenium web Driver in TestNG and I have a scenario where I am running multiple tests sequentially (refer below)

@Test(priority         


        
3条回答
  •  抹茶落季
    2020-12-13 01:20

    Here is better and tested version of WaitForPageLoad implementation in C#.Net

    public void WaitForPageLoad(int maxWaitTimeInSeconds) {
        string state = string.Empty;
        try {
            WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(maxWaitTimeInSeconds));
    
            //Checks every 500 ms whether predicate returns true if returns exit otherwise keep trying till it returns ture
            wait.Until(d = > {
    
                try {
                    state = ((IJavaScriptExecutor) _driver).ExecuteScript(@"return document.readyState").ToString();
                } catch (InvalidOperationException) {
                    //Ignore
                } catch (NoSuchWindowException) {
                    //when popup is closed, switch to last windows
                    _driver.SwitchTo().Window(_driver.WindowHandles.Last());
                }
                //In IE7 there are chances we may get state as loaded instead of complete
                return (state.Equals("complete", StringComparison.InvariantCultureIgnoreCase) || state.Equals("loaded", StringComparison.InvariantCultureIgnoreCase));
    
            });
        } catch (TimeoutException) {
            //sometimes Page remains in Interactive mode and never becomes Complete, then we can still try to access the controls
            if (!state.Equals("interactive", StringComparison.InvariantCultureIgnoreCase))
                throw;
        } catch (NullReferenceException) {
            //sometimes Page remains in Interactive mode and never becomes Complete, then we can still try to access the controls
            if (!state.Equals("interactive", StringComparison.InvariantCultureIgnoreCase))
                throw;
        } catch (WebDriverException) {
            if (_driver.WindowHandles.Count == 1) {
                _driver.SwitchTo().Window(_driver.WindowHandles[0]);
            }
            state = ((IJavaScriptExecutor) _driver).ExecuteScript(@"return document.readyState").ToString();
            if (!(state.Equals("complete", StringComparison.InvariantCultureIgnoreCase) || state.Equals("loaded", StringComparison.InvariantCultureIgnoreCase)))
                throw;
        }
    }
    

提交回复
热议问题