Evelyn Harumi
Evelyn Harumi

Reputation: 49

Selenium C# - ElementExists without "By locator"

I'm working with Selenium WebDriver for a few weeks, my Project is almost done, but there's something taking my patience away.

In my project, I divided everything in classes, so there's a class where I put my elements, declared as the following example (and in the same class, I put the functions implemented on my tests):

    [FindsBy(How = How.XPath, Using = "//div[@class='k-widget k-window' and not(contains(@style,'display: none;'))]//button[text()='Confirmar']")]
    private IWebElement GenericConfirmButton { get; set; }

One of my functions is:

    private void ClickConfirmButtonIfVisible()
    {
        if (GenericConfirmButton.IsVisible())
            GenericConfirmButton.SetClick();
    }

The function IsVisible() performs the code below (its in another class):

    public static bool IsVisible(this IWebElement element)
    {
        try
        {
            new WebDriverWait(GeneralProperties.Driver, TimeSpan.FromMilliseconds(0))
                .Until(ExpectedConditions.ElementToBeClickable(element));
            if (element.Enabled && element.Displayed)
            {
                return true;
            }
            else
            return false;
        }
        catch (WebDriverTimeoutException)
        {
            return false;
        }
    }

So, my problem is: this function IsVisible() is taking about 5 seconds to execute (if the element does not exist). My purpose with this is that, if I hit the button "Confirmar", it must check if the element exists and, if not, return false.

I've already tried to use ElementExists instead of ElementToBeClickable but I don't know how to do that (because I use an separeted class to declare the IWebElement element and this function needs a By declaration). I would like to use ElementExists (I believe it would run faster than now). Or, if you know any other way and could help me, I really would aprecciate it.

That's all. Thanks!

Upvotes: 2

Views: 362

Answers (1)

mrfreester
mrfreester

Reputation: 1991

It is waiting 5 seconds because somewhere in your code you are setting ImplicitlyWait on the driver. You can remove that, but if you have other tests that rely on Implicit Waits those could be impacted.

Generally speaking, I would suggest only using explicit waits, partially do to an issue with unexpected wait times combining explicit and implicit waits.

This issue can also be avoided by making sure your test logic doesn't get too clever by avoiding if statements in your logic. In this case, basically your test case should know if the button is there or not, so the logic should reflect that.

Upvotes: 3

Related Questions