Javascript test case for Keypress event

177 Views Asked by At

The code of my JS file is mentioned below:

 $('#HeaderLink').keypress(function (e) {

     var key = e.which;

     if (key == 13)        
     {

         TravelRegistration.expandSection();
     }
 });

When I run following Javascript Test Case (Qunitjs and Blanket.js), it runs successfully but its not able to call 'expandSection' function. Code coverage only covers only first line of code that is $('#HeaderLink').keypress(function (e) {

Someone please assist how to write test case so that I can call my function.

Code of TEST CASE

test("expandSection test", 1, function () {
    var div = $('<div>').appendTo("body");

    $('<a id="HeaderLink" >').appendTo(div);
    $("#HeaderLink").trigger("keypress" , 13);
    var result = TravelRegistration.expandSection();
    equal(undefined, result, "passed");
    $("div").remove();
});
1

There are 1 best solutions below

0
Christoph On

You need to create a custom jQuery Event for it:

var e = $.Event("keypress", { which: 13 });
$("#HeaderLink").trigger(e);

See jQuery documentation for it.