首页 > 解决方案 > 当页面实际上是一种方法时,如何等待页面加载?

问题描述

我的 selenium 脚本中有许多方法,它们基本上只是调用一个新页面,即 ChooseUserMgt();。可以应用哪些页面加载/等待/显式/隐式等待来确保它成功启动,因为有时加载需要很长时间?

 [TestInitialize]
        public void Setup()
        {
            _regRep = new UserRegRep(driver);
            CreateRepos();
            runTime = DateTime.Now.ToString("MMddHHmmssfff");
            userName = "Jonny" + objCommon.RandomString(8, true);
            emailID = "JonnySmithy" + runTime + "@hotmail.com";

            // Start the user mangaement tests on the user management page
            **ChooseUserMgt();**
        }

这是方法:

[TestMethod]
        [TestCategory("Cat1")]
        public void ChooseUserMgt()
        {
            //Choose the User Managment menu
            IJavaScriptExecutor executor = (IJavaScriptExecutor)driver;
            executor.ExecuteScript("arguments[0].click()", _regRep.SystemIcon);
            System.Threading.Thread.Sleep(2000);
            IJavaScriptExecutor executor1 = (IJavaScriptExecutor)driver;
            executor1.ExecuteScript("arguments[0].click()", _regRep.UserMgmtLink);
            System.Threading.Thread.Sleep(2000);
        }

标签: c#selenium-webdriver

解决方案


我会采取完全不同的方法。

对于单击,我需要两种方法 - WaitForControlToBeClickable 和 Click。

第一种方法是确保元素可见。这可以在您需要的所有其他操作方法中重复使用。

  static bool WaitForControlToBeClickable(By SeleniumObject, int waitFor = 10)
        {
            try
            {
                WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(waitFor));
                wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(SeleniumObject));
                return true;
            }
            catch (Exception er)
            {
                return false;
                throw er;
            }

        }

接下来,您将创建一个方法来单击并调用内部的先前方法:

        public void Click(By SeleniumObject)
        {
            WaitForControlClickable(SeleniumObject);
            driver.FindElement(SeleniumObject).Click();
        }

您可以将它们存储在另一个类 - CommonActions 中。因此,一旦您在测试中实例化它,您就可以这样调用它:

commonAction.Click(MyObject);

我还建议将您的对象单独存储在您通过操作调用以创建测试的对象存储库中。


推荐阅读