In My Personal Experience,If you develop a feature in Javascript, you must add Unit Test cases for your code.Having Unit Test Cases will really helpful in the following scenarios.
1)While Refactoring the code for improving the code
2)While Updating the code, To introduce an Enhancement
Comprehensively,If you are going to change your code,Unit test cases will really give you confidence,The changes added by you did not break the existing implementation.
In-Browser Testing:
Basically,In-Browser Testing Frameworks allows you to run your test cases by loading the html page in the browser.Following are some of the popular In-Browser testing frame works available
1)Qunit.js
2)jsUnit
I prefer Qunit.js,because it is very easy to integrate (doesn’t need any dependencies) and most popularly used now.If you want to start writing Unit Test cases using Qunit.js.Here is my help for you.Please Follow these steps
Step1:
Create an Html File and include the Qunit.js and Qunit.css ,Which will be used for running the test suites created via In-Browser Testing.
Example:
<script type=”text/javascript” src=”http://code.jquery.com/jquery-latest.js”></script>
<script type=”text/javascript” src=”http://code.jquery.com/qunit/git/qunit.js”></script>
<h1 id=”qunit-header”>QUnit example</h1>
<h2 id=”qunit-banner”></h2>
<h2 id=”qunit-userAgent”></h2>
<div id=”qunit-fixture”>test markup, will be hidden</div>
Step2:
Create javascript file, To write the unit test cases needed to test javascript code. Include this file in your test html page .
Example:
If your javascript file name is dragdrop.js, then your new javascript test file will be dragdrop.test.js.Include both the dragdrop.js and dragdrop.test.js in the above said html file.
Step3:
Create a module to test a Feature / Function.In Setup and Tear down methods initialize and destroy the variables needed for testing.
module(“Module Name”,
{
setup:function()
{
setup logic should be written is done here,called before each test case (test() method)
this — – refers to the module.
this.variableName — to add a variable,which can be accessed inside the test case
Add Html elements,if needed for testing
},
teardown:function()
{
clean up is done here, called after each test case execution (test() method)
this.variableName = null — to remove the variables,added during the setup method
Remove Html elements added while setup
}
});
Step4:
Create Test Cases,To test the javascript code using assertions
Example:
Test Case: Test Case Should be written after a module
test(“Name of the test case”,
function(){
1)call the function to be tested
2)assert the results
Assertions:
equal(actualResult,expectedResult,message);
notEqual(actualResult,expectedResult,message);
}
});
Following is the sample code(Template), which will be useful for writing a testcase using Qunits
module(“test”,
{
setup:function(){},
teardown=function(){}
}
);
test(“Name”,function(){ equal(A,E,M); notEqual(A,E,M);
});
A — actual result
E — expected Result
M — Message