HtmlUnit – JavaScript T

电脑杂谈  发布时间:2017-03-30 11:05:12  来源:网络整理
htmlunithtmlunit

A frequent question we get is "how do I test my JavaScript?".There is nothing really specific for using JavaScript, it is automatically processed.So, you just need to .getPage(), find the element to click(), and then check the result.Tests for complex JavaScript libraries are included in HtmlUnit test base, you can find itherewhich is useful to get an idea.

Usually, you should wait() or sleep() a little, as HtmlUnit can finish before the AJAX response isretrieved from the server, please read .

Below are some examples:

Lets say that we have a page containing JavaScript that will dynamicallywrite content to the page. The following html will dynamically generatefive textfields and place them inside a table. Each textfield will havea unique name created by appending the index to the string "textfield".

We would likely want to test that the five text fields were created sowe could start with this.

We might also want to check off-by-one errors by ensuring thatit didn't create "textfield0" or "textfield6". Trying to get anelement that doesn't exist will cause an exception to be thrownso we could add this to the end of the previous test.

Often you want to watch alerts triggered by JavaScript.

Alerts are tracked by an AlertHandler which will be called wheneverthe JavaScript alert() function is called. In the following test,we register an alert handler which just saves all messages into alist. When the page load is complete, we compare that list ofcollected alerts with another list of expected alerts to ensurethey are the same.

Handling prompt dialogs, confirm dialogs and status line messageswork in the same way as alerts. You register a handler of theappropriate type and it will get notified when that method is called.See WebClient.setPromptHandler(), WebClient.setConfirmHandler() andWebClient.setStatusHandler() for details on these.

Most event handlers are already implemented: onload, onclick, ondblclick, onmouseup, onsubmit, onreadystatechange, ...They will be triggered at the appropriate time just like in a "real browser".

If the event that you wish to test is not yet supported then you candirectly invoke it through the ScriptEngine. Note that while the scriptengine is publiclyaccessible, we do not recommend using it directly unless you have noother choice. It is much better to manipulate the page as a user wouldby clicking on elements and shifting the focus around.


本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-38446-1.html

    相关阅读
      发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

      热点图片
      拼命载入中...