Selenium chaining IWebElement actions in C#



  • [FindsBy(How = How.XPath, Using = "//input[@id='Username']")]
    private IWebElement txtUsername;
    
    public void EditTxtUsername(string text)
    {
        txtUsername.Clear();
        txtUsername.SendKeys(text);
    }
    

    Is there a way in C# to chain the two actions into txtUsername.Clear().SendKeys(text);?



  • I would advise against chaining at this level, for reasons stated at Chaining WebElement actions.

    The preferred approach would be to have a helper method, reducing the code duplication of clearing a field (and possibly other actions) every time you want to set text.

    public void SetText(IWebElement element, string text)
    {
        element.Clear();
        element.SendKeys(text);
    }
    

    Extensions methods could also work but due to overloading restrictions, the method names would have to be different (or the number of arguments), for example:

    public static IWebElement MyClear(this IWebElement element)
    {
        element.Clear();
        return element;
    }
    
    public static IWebElement MySendKeys(this IWebElement element, string text)
    {
        element.SendKeys(text);
        return element;
    }
    


Suggested Topics

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