Re: How to test event handlers with Jasmine (or another test framework)?

2,618 views
Skip to first unread message

Alberto Leal

unread,
Jun 8, 2012, 3:22:39 PM6/8/12
to Jasmine
Hi Nicola,

I think you could add another test without mocking $.cookie, just to
make sure that your js function (handle_set_tab_cookie) works as
expected, saving the value into a cookie.

I see that your function retrieves the href attr:
var active = $( this ).attr( 'href' );

What happens if somebody else calls that function with an element that
doesn't have that attr? -- This function doesn't deal this situation.
So, maybe you should add a validation on that. And, add another test
to it =)

- Create a test to check if the value could be retrieved from the
cookie.
- Create another test passing an invalid element to your functions -- $
( 'div' ).click( event_handlers.handle_set_tab_cookie );


thanks,

On Jun 7, 1:47 pm, Nicola Peluchetti <nicola.peluche...@gmail.com>
wrote:
> Ive got to test a very simple situation, i'm saving the clicked tab in a
> cookie so that when i reload the page i open the correct tab. This is what
> i'm testing
>
> $( 'ul.nav-tabs a' ).click( event_handlers.handle_set_tab_cookie );
>
> var handle_set_tab_cookie = function( e ) {
>     var active = $( this ).attr( 'href' );
>     $.cookie( 'feeds_active_tab', active );
>
> };
>
> What i was thinking to do to test this is:
>
> 1) Create the required html in the beforeEach() function
>
> beforeEach(function() {
>     var html = "all the needed html here";
>     $('body').append(html);
>
> });
>
> 2) attach the event handler, set-up the spies and trigger the click event
>
> it( "Calls jQuery coookie passing it's href as a parameter", function() {
>     // Attach the event handler
>     $( 'ul.nav-tabs a' ).click( event_handlers.handle_set_tab_cookie );
>     // Set up spies
>     spyOn($, 'cookie');
>     // Start the test
>     $('a.facebook').trigger( 'click' );
>     // verify that it has been called with the correct parameter
>     expect($.cookie).toHaveBeenCalled();
>     expect($.cookie).toHaveBeenCalledWith('facebook');
>
> } );
>
> Is this the correct way to test?I'm new to testing javascript, i just
> wanted to be sure i'm going in the righ direction

Nicola Peluchetti

unread,
Jun 8, 2012, 3:51:50 PM6/8/12
to jasmi...@googlegroups.com
Thanks for the suggestions, you are totally right :)
Reply all
Reply to author
Forward
0 new messages