Selenium tricks

Waiting until the page loads

    WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
    wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));

Selecting a sibling using xPath

    // Just in one sentence:
    var sibling = driver.FindElement(By.XPath("//input[@id='myId']/following-sibling::span[@class='someClass']"));

    // Or if you already had the first one:
    var someElement = driver.FindElement(By.Id("myIdentifier"));
    var icon = someElement.FindElement(By.XPath("//following-sibling::span[@class='someClass']"));

Hovering over an element

I found myself in trouble when trying to test a feature that required hovering the mouse over an element. It seems there is an easy way of doing it using Selenium with an action and:

            var icon = driver.FindElement(By.Id("myIcon"));

            var action = new Actions(driver);
            action.MoveToElement(icon); //I think in theory this is how it should be done
            action.MoveToElement(icon).Click().Build().Perform(); // Though many people around stackoverflow suggested to use this other one.
            action.MoveByOffset(icon.Location.X, icon.Location.Y); //And I even tried this one.

Unfortunately none of them work due to me using jQuery to trigger the event with a .hover() and jQuery using different events to trigger this, those are ‘mouseenter’ and ‘mouseleave’, but not ‘mouseover’, as Kevin explains here. Thanks Kevin.

So the solution I implemented was to activate the event using the same jQuery:

            var js = "$('#myIcon').trigger('mouseenter')";
            ((IJavaScriptExecutor)driver).ExecuteScript(js);

And that worked perfectly.

Leave a Reply

Close Bitnami banner
Bitnami