Search code examples
c#jquerytestingseleniumselenium-rc

C# Selenium RC - How to test a jQuery button click?


What is the correct way to run a jQuery .click() in a selenium test? The element being clicked is a hyperlink.

HTML:

<div id="buttons">
    <a class="button" id="btnRun" href="javascript:void(0)">Run</a>
</div>
<div id="output" />

jQuery

$(document).ready(function () {
    $('#btnRun').click(function () {
       $("#output").html("hello world");
    });
})

Selenium:

[Test]
public void TestOutput()
{
    selenium_local = new DefaultSelenium("localhost", 4444, 
                                         "*firefox", "https://localhost");
    selenium_local.Start(); 

    selenium_local.Open("/TestPage");
    selenium_local.WaitForPageToLoad("30000");
    Assert.That(selenium_local.IsElementPresent("id=btnRun"), Is.True);

    selenium_local.Click("id=btnRun");
    Thread.Sleep(5000);

    // also tried without success:
    // selenium_local.FireEvent("id=btnRun","click");
    // selenium_local.Click("xpath=//a[@id='btnRun']");
    // selenium_local.Click("dom=document.getElementById('btnRun')");

    Assert.That(selenium.GetValue("id=output"), Is.EqualTo("hello world"));
}

When I run the test the button click does not occur, and after the 2nd WaitForPageToLoad, the test finishes and reports failure (because the text hello world was not found, because the button click never occurred)


Solution

  • (Note: I use selenium with java, so there might be a difference, but I strongly doubt it)

    I have similar problems sometimes, but we're using plain-ol'-javascript in some places, gwt in others, and mootools in some other places (don't ask why so many) for our different ajax calls so it's possible our problems are completely unrelated. But, maybe I can help regardless.

    I have to sometimes use mouseOver then click. Sometimes I even have to do mouseDown and then mouseUp. Or a combination of the two. And even in some cases we have to retry the click.

    (Also, unless clicking the link/button causes a full page load, the WaitForPageToLoad is going to cause issues because it waits for a page loaded event. Here's how I ended up waiting for Ajax calls to finish, however you should be able to come up with a cleaner solution if you're only using JQuery)