I am currently u开发者_C百科nit testing some javascript, where it handles an event raised by clicking on a certain item in the window. Below is a snipet of the code:
function someFunction()
{
var evt = window.event ? window.event : event;
if (evt == null) { return; }
var nodeElement = evt.srcElement;
if (nodeElement == null) { return; }
.
.
.
}
My current approach is to try to create a custom event in my test file which will populate window.event so I can at least get to test the nodeElement == null part. But I am having difficulties doing so (being not from a Javascript backgound). How do I actually create a custom event (in IE)? I'm currently doing unit testing using JsTestDriver so no html file is used. I do not mind using jQuery or just plain Javascript solution.
Thanks.
I would definitely use jQuery (or some other framework). It will make your life easier. I am sure every browser will have a different way of triggering the event.
http://docs.jquery.com/Events
With jQuery you just do something like
$(window).trigger("eventname")
I currently wrote a blog post series about custom events in jQuery. You can use .trigger
and .bind
and it is really powerful.
As alex has pointed out in his comment, you can use jQuery to create events with
$("css selector here").jQueryEventFunction(functionToCall);
So, following your example, if you want to invoke someFunction
when a label is clicked you can do:
$("#label-id").click(someFunction);
Now, if you want to simulate clicking it
$("#label-id").click();
And that will do it.
EDIT For the window event you can use
$(window).click(someFunction);
That will bind any click done in the window to someFunction
. And if you call $(window).click();
a click event will be simulated, calling someFunction
.
精彩评论