In a Webdriver UI test, do you have to check for the existence of every element you use?



  • I'm working on my first Selenium/Webdriver tests, and I have a rather basic question. I was thinking of adding a login helper method, since it's going to be a rather basic feature of every test. I created it, and have a question-how often do you have to check for the existence of an element?

    public static bool Login(ChromeDriver driver)
    {
        driver.Url = "http://testing-site.com/";
        IWebElement userbox = driver.FindElementById("UserName");
        IWebElement passbox = driver.FindElementById("Password");
    
        IWebElement submitBtn = driver.FindElementById("submit-login-btn");
        userbox.SendKeys("testuser");
        passbox.SendKeys("testpassword");
        submitBtn.Click();
    
    }
    

    I see a lot of links like https://thefriendlytester.co.uk/2014/01/checking-if-element-is-present-with.html about creating helper methods to check for the existence of elements. Should I call that every time I access an element of the DOM? Or can I just wrap stuff in a try/catch block and not worry about it? Should I use those helper methods to test for the existence of an element instead of try/catch blocks?



  • What I found is a SO question where it's stated that

    that C# will look for the Element immediately and when it is not found will crash with a "No Such Element" exception

    So when you encounter these exception you should check if the element is really where you think it is and wait for it if needed. Catching these kind of exceptions is usually not recommended.

    Also take a look at the page object model using webelements in different places



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2