views:

337

answers:

3

Hi all:

I am currently unit 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.

A: 

I currently wrote a blog post series about custom events in jQuery. You can use .trigger and .bind and it is really powerful.

stoimen
+1  A: 

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")
Victor
A: 

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.

MaLKaV_eS
@MaKLaV_eS: what if I just want to create a window event? From what I know, in order to trigger an event, all I need to do is to click in the browser somewhere and it will trigger an event. I want to catch that event so I can at least be able to test the latter condition in my javascript.
BeraCim
See edited answer. Hope this is what you want.
MaLKaV_eS
@MaKLaV_eS: Thanks for the update. I have tried your code, and also followed the examples from http://docs.jquery.com/Events/click, but its still not working. Looks like the problem has something to do with JsTestDriver itself.
BeraCim