2

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...

nrofis
  • 8,975
  • 14
  • 58
  • 113

2 Answers2

0

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.

Community
  • 1
  • 1
Mosty Mostacho
  • 42,742
  • 16
  • 96
  • 123
  • Good point. I assumed you were performing an AJAX call in your `...`. Either way, if it is asynchronous then you can handle it the same way. Now I see what might be the issue: `location.search` is performing another HTTP request. So you should wait for the request to finish. Again, this should be handled as I explained in the other question by applying a manual delay – Mosty Mostacho Jun 28 '14 at 13:53
  • No, in the `...` code its just for setting variables. No more actions do in this function. – nrofis Jun 28 '14 at 14:24
0

I fell also in similar issue. My html link is triggering javascript using events.

My not working test code was:

HtmlAnchor anchor = element.getFirstByXPath("//a[@id='...']");
anchor.click(); // This is not firing events on js side!!!!

How it works:

HtmlAnchor anchor = element.getFirstByXPath("//a[@id='...']");
anchor.fireEvent("click"); // JS running which listening on click events!
Michael Hegner
  • 5,555
  • 9
  • 38
  • 64