Skip to content
Advertisement

HtmlUnit wait for onclick event

I have this web code:

<a id="btn">Click</a>

<script>
    $('document').ready(function() {
         $('#btn').click(function() {
             ...
             location.search = $.params({click: '1'});
         });
    });
</script>

This code work perfectly in Chrome.

But I want to test it with HtmlUnit. I wrote:

    page= (HtmlPage) ((HtmlAnchor) page.getDocumentElement().querySelector("#btn")).click();
    assertThat(page.getUrl().getQuery(), containsString("click=1"));

This code works randomly. Sometime the test passed and sometimes failed. I think it is due because of the asynchronous call to JS, but I couldn’t solve it.

So how can I test it?

Besides, there is better solution to test web site insted HtmlUnit? HtmlUnit disappointed…

Advertisement

Answer

The fact that your code works randomly might mean that there is a timing issue in the asynchronous JS call. I have explained the best alternative to come around these kind of issues in this other question: Get the changed HTML content after it’s updated by Javascript? (htmlunit)

Answering your second question, HtmlUnit is a pain in the neck when it comes to JS. Maybe Selenium with the native browser (eg: IE) drivers are a better alternative. Plan C would be PhantomJS but it is not a Java library.

Advertisement