QUnit - Quick Guide

Testing is the process of checking the functionality of the application whether it is working as per the requirements and to ensure that at the developer level, unit testing comes into picture. Unit testing is the testing of a single entity (class or method). Unit testing is very essential for every software organization to offer quality products to their clients.
Unit testing can be done in two ways as mentioned in the following table.
QUnit is a unit testing framework for JavaScript programming language. It is important in the test driven development, and is used by jQuery, jQuery UI, and jQuery Mobile projects. QUnit is capable of testing any generic JavaScript codebase.
QUnit promotes the idea of "first testing then coding", which emphasizes on setting up the test data for a piece of code, which can be tested first and then implemented. This approach is like "test a little, code a little, test a little, code a little..." which increases the programmer’s productivity and the stability of program code reducing the programmer’s stress and the time spent on debugging.
QUnit is an open source framework used for writing and running tests. Following are its most prominent features −
QUnit provides Assertions for testing expected results.
QUnit provides Assertions for testing expected results.
QUnit provides Test fixtures for running tests.
QUnit provides Test fixtures for running tests.
QUnit tests allow to write code faster, which increases the quality.
QUnit tests allow to write code faster, which increases the quality.
QUnit is elegantly simple. It is less complex and takes less time.
QUnit is elegantly simple. It is less complex and takes less time.
QUnit tests can be run automatically and they check their own results and provide immediate feedback. There's no need to manually comb through a report of test results.
QUnit tests can be run automatically and they check their own results and provide immediate feedback. There's no need to manually comb through a report of test results.
QUnit tests can be organized into test suites containing test cases and even other test suites.
QUnit tests can be organized into test suites containing test cases and even other test suites.
QUnit shows test progress in a bar that is green if the test is going fine, and it turns red when a test fails.
QUnit shows test progress in a bar that is green if the test is going fine, and it turns red when a test fails.
A Unit Test Case is a part of code which ensures that another part of the code (method) works as expected. To achieve the desired results quickly, test framework is required. QUnit is a perfect unit test framework for JavaScript programming language.
A formal written unit test case is characterized by a known input and by an expected output, which is worked out before the test is executed. The known input should test a precondition and the expected output should test a post-condition.
There must be at least two unit test cases for each requirement: one positive test and one negative test. If a requirement has sub-requirements, each sub-requirement must have at least two test cases as positive and negative.
There are two ways to use QUnit.
Local Installation − You can download QUnit library on your local machine and include it in your HTML code.
Local Installation − You can download QUnit library on your local machine and include it in your HTML code.
CDN Based Version − You can include QUnit library into your HTML code directly from Content Delivery Network (CDN).
CDN Based Version − You can include QUnit library into your HTML code directly from Content Delivery Network (CDN).
Go to the https://code.jquery.com/qunit/ to download the latest version available.
Go to the https://code.jquery.com/qunit/ to download the latest version available.
Place the downloaded qunit-git.js and qunit-git.css file in a directory of your website, e.g. /jquery.
Place the downloaded qunit-git.js and qunit-git.css file in a directory of your website, e.g. /jquery.
You can include qunit-git.js and qunit-git.css files in your HTML file as follows −
<html> 
   <head> 
      <meta charset = "utf-8"> 
      <title>QUnit basic example</title> 
      <link rel = "stylesheet" href = "/jquery/qunit-git.css"> 
      <script src = "/jquery/qunit-git.js"></script> 
   </head> 
   
   <body> 
      <div id = "qunit"></div> 
      <div id = "qunit-fixture"></div>  
      <script> 
         QUnit.test( "My First Test", function( assert ) { 
            var value = "1"; 
            assert.equal( value, "1", "Value should be 1" ); 
         }); 
      </script> 
   </body> 
</html>
This will produce following result −
You can include QUnit library into your HTML code directly from Content Delivery Network (CDN).
Let us rewrite the above example using QUnit library from jQuery CDN.
<html>
   <head>
      <meta charset = "utf-8">
      <title>QUnit basic example</title>
      <link rel = "stylesheet" href = "https://code.jquery.com/qunit/qunit-1.22.0.css">
      <script src = "https://code.jquery.com/qunit/qunit-1.22.0.js"></script>
   </head>
   
   <body>
      <div id = "qunit"></div>
      <div id = "qunit-fixture"></div> 
      <script>
         QUnit.test( "My First Test", function( assert ) {
            var value = "1";
            assert.equal( value, "1", "Value should be 1" );
         });
      </script>
   </body>
</html>
This will produce following result −
Tests completed in 2 milliseconds.1 assertions of 1 passed, 0 failed.
My First Test (1)Rerun0 msValue should be 1@ 0 msSource:     at https://www.tutorialspoint.com/qunit/src/first_application.htm:12:16
My First Test (1)Rerun0 msValue should be 1@ 0 msSource:     at https://www.tutorialspoint.com/qunit/src/first_application.htm:12:16
Value should be 1@ 0 ms
Value should be 1@ 0 ms
Source:     at https://www.tutorialspoint.com/qunit/src/first_application.htm:12:16
Now we'll show you a step-by-step process to get a kickstart in QUnit using a basic example.
qunit.js of Qunit library represents the test runner and test framework.
<script src = "https://code.jquery.com/qunit/qunit-1.22.0.js"></script> 

qunit.css of Qunit library styles the test suite page to display the test results.
<link rel = "stylesheet" href = "https://code.jquery.com/qunit/qunit-1.22.0.css">

Add two div elements with id = "qunit" and "qunit-fixture". These div elements are required and provide the fixture for tests.
<div id = "qunit"></div>
<div id = "qunit-fixture"></div>

function square(x) {
   return x * x;
}
Make a call to the QUnit.test function, with two arguments.
Name − The name of the test to display the test results.
Name − The name of the test to display the test results.
Function − Function testing code, having one or more assertions.
Function − Function testing code, having one or more assertions.
QUnit.test( "TestSquare", function( assert ) {
   var result = square(2);
   assert.equal( result, "4", "square(2) should be 4." );
});
Now let us see the complete code in action.
<html>
   <head>
      <meta charset = "utf-8">
      <title>QUnit basic example</title>
      <link rel = "stylesheet" href = "https://code.jquery.com/qunit/qunit-1.22.0.css">
      <script src = "https://code.jquery.com/qunit/qunit-1.22.0.js"></script>
   </head>
   
   <body>
      <div id = "qunit"></div>
      <div id = "qunit-fixture"></div> 
      
      <script>
         function square(x) {
            return x * x;
         }
         QUnit.test( "TestSquare", function( assert ) {
            var result = square(2);
            assert.equal( result, "4", "square(2) should be 4." );
         });
      </script>
   </body>
</html>
Load the page in the browser. The test runner calls QUnit.test() when the page gets loaded and adds the test to a queue. Execution of test case is deferred and controlled by the test runner.
You should see the following result −
Tests completed in 7 milliseconds.1 assertions of 1 passed, 0 failed.
TestSquare (1)Rerun1 mssquare(2) should be 4.@ 0 msSource:     at https://www.tutorialspoint.com/qunit/src/basic_usage.htm:15:16
TestSquare (1)Rerun1 mssquare(2) should be 4.@ 0 msSource:     at https://www.tutorialspoint.com/qunit/src/basic_usage.htm:15:16
square(2) should be 4.@ 0 ms
square(2) should be 4.@ 0 ms
Source:     at https://www.tutorialspoint.com/qunit/src/basic_usage.htm:15:16
Header − Test suite header displays the page title, a green bar when all tests are passed. Otherwise, a red bar when at least one test has failed, a bar with a three checkboxes to filter the test results, and a blue bar with the navigator.userAgent text to display the browser details.
Header − Test suite header displays the page title, a green bar when all tests are passed. Otherwise, a red bar when at least one test has failed, a bar with a three checkboxes to filter the test results, and a blue bar with the navigator.userAgent text to display the browser details.
Hide passed tests checkbox − To hide the passed test cases and showcase only the failed test cases.
Hide passed tests checkbox − To hide the passed test cases and showcase only the failed test cases.
Check for globals checkbox − To show the list of all properties on the window object, before and after each test, then check for differences. Modification to the properties will fail the test.
Check for globals checkbox − To show the list of all properties on the window object, before and after each test, then check for differences. Modification to the properties will fail the test.
No try-catch checkbox − To run test cases outside of a try-catch block so that in case of a test throwing an exception, the testrunner will die and show native exception.
No try-catch checkbox − To run test cases outside of a try-catch block so that in case of a test throwing an exception, the testrunner will die and show native exception.
Summary − Shows the total time taken to run the test cases. Total test cases run and failed assertions.
Summary − Shows the total time taken to run the test cases. Total test cases run and failed assertions.
Contents − Shows the test results. Each test result has the name of the test followed by failed, passed, and total assertions. Each entry can be clicked to get further details.
Contents − Shows the test results. Each test result has the name of the test followed by failed, passed, and total assertions. Each entry can be clicked to get further details.
Some of the important Category of QUnit are −
It provides a set of assert methods.
async()
Instruct QUnit to wait for an asynchronous operation.
deepEqual()
A deep recursive comparison, working on primitive types, arrays, objects, regular expressions, dates, and functions.
equal()
A non-strict comparison, roughly equivalent to JUnit's assertEquals.
expect()
Specify how many assertions are expected to run within a test.
notDeepEqual()
An inverted deep recursive comparison, working on primitive types, arrays, objects, regular expressions, dates, and functions.
notEqual()
A non-strict comparison, checking for inequality.
notOk()
A boolean check, inverse of ok() and CommonJS's assert.ok(), and equivalent to JUnit's assertFalse(). Passes if the first argument is false.
notPropEqual()
A strict comparison of an object's own properties, checking for inequality.
notStrictEqual()
A strict comparison, checking for inequality.
ok()
A boolean check, equivalent to CommonJS's assert.ok() and JUnit's assertTrue(). Passes if the first argument is true.
propEqual()
A strict type and value comparison of an object's own properties.
push()
Report the result of a custom assertion.
strictEqual()
A strict type and value comparison.
throws()
Test if a callback throws an exception, and optionally compare the thrown error.
It provides a set of asynchronous operations.
async()
Instruct QUnit to wait for an asynchronous operation.
QUnit.asyncTest()
DEPRECATED: Add an asynchronous test to run. The test must include a call to QUnit.start().
QUnit.start()
PARTIALLY DEPRECATED: Start running the tests again after the testrunner was stopped. See QUnit.stop() and QUnit.config.autostart.
QUnit.stop()
DEPRECATED: Increase the number of QUnit.start() calls the testrunner should wait for before continuing.
QUnit.test()
Add a test to run.
When integrating QUnit into other tools like CI servers, these callbacks can be used as an API to read the test results.
QUnit.begin()
Register a callback to fire whenever the test suite begins.
QUnit.done()
Register a callback to fire whenever the test suite ends.
QUnit.log()
Register a callback to fire whenever an assertion completes.
QUnit.moduleDone()
Register a callback to fire whenever a module ends.
QUnit.moduleStart()
Register a callback to fire whenever a module begins.
QUnit.testDone()
Register a callback to fire whenever a test ends.
QUnit.testStart()
Register a callback to fire whenever a test begins.
These methods and properties are used as utility helpers and to configure QUnit. For example, to adjust the runtime behavior directly, extend the QUnit API via custom assertions, etc.
QUnit.assert
Namespace for QUnit assertions.
QUnit.config
Configuration for QUnit.
QUnit.dump.parse()
Advanced and extensible data dumping for JavaScript.
QUnit.extend()
Copy the properties defined by the mixin object into the target object.
QUnit.init()
DEPRECATED: Re-initialize the test runner.
QUnit.push()
DEPRECATED: Report the result of a custom assertion.
QUnit.reset()
DEPRECATED: Reset the test fixture in the DOM.
QUnit.stack()
Returns a single line string representing the stacktrace (call stack).
It provides a set of testing operations.
QUnit.assert
Namespace for QUnit assertions.
QUnit.asyncTest()
DEPRECATED: Add an asynchronous test to run. The test must include a call to QUnit.start().
QUnit.module()
Group related tests under a single label.
QUnit.only()
Adds a test to exclusively run, preventing all other tests from running.
QUnit.skip()
Adds a test like object to be skipped.
QUnit.test()
Adds a test to run.
All the assertions are in the Assert Category.
This category provides a set of assertion methods useful for writing tests. Only failed assertions are recorded.
async()
Instruct QUnit to wait for an asynchronous operation.
deepEqual()
A deep recursive comparison, working on primitive types, arrays, objects, regular expressions, dates, and functions.
equal()
A non-strict comparison, roughly equivalent to JUnit's assertEquals.
expect()
Specify how many assertions are expected to run within a test.
notDeepEqual()
An inverted deep recursive comparison, working on primitive types, arrays, objects, regular expressions, dates, and functions.
notEqual()
A non-strict comparison, checking for inequality.
notOk()
A boolean check, inverse of ok() and CommonJS's assert.ok(), and equivalent to JUnit's assertFalse(). Passes if the first argument is false.
notPropEqual()
A strict comparison of an object's own properties, checking for inequality.
notStrictEqual()
A strict comparison, checking for inequality.
ok()
A boolean check, equivalent to CommonJS's assert.ok() and JUnit's assertTrue(). Passes if the first argument is true.
propEqual()
A strict type and value comparison of an object's own properties.
push()
Report the result of a custom assertion.
strictEqual()
A strict type and value comparison.
throws()
Test if a callback throws an exception, and optionally compare the thrown error.
Let's try to cover most of the above mentioned methods in an example.
<html>
   <head>
      <meta charset = "utf-8">
      <title>QUnit basic example</title>
      <link rel = "stylesheet" href = "https://code.jquery.com/qunit/qunit-1.22.0.css">
      <script src = "https://code.jquery.com/qunit/qunit-1.22.0.js"></script>
   </head>
   
   <body>
      <div id = "qunit"></div>
      <div id = "qunit-fixture"></div> 
      <script>
         QUnit.test( "TestSuite", function( assert ) {
            //test data
            var str1 = "abc";
            var str2 = "abc";
            var str3 = null;
            var val1 = 5;
            var val2 = 6;
            var expectedArray = ["one", "two", "three"];
            var resultArray =  ["one", "two", "three"];

            //Check that two objects are equal
            assert.equal(str1, str2, "Strings passed are equal.");
			
            //Check that two objects are not equal
            assert.notEqual(str1,str3, "Strings passed are not equal.");

            //Check that a condition is true
            assert.ok(val1 < val2, val1 + " is less than " + val2);
			
            //Check that a condition is false
            assert.notOk(val1 > val2, val2 + " is not less than " + val1);

            //Check whether two arrays are equal to each other.
            assert.deepEqual(expectedArray, resultArray ,"Arrays passed are equal.");
			
            //Check whether two arrays are equal to each other.
            assert.notDeepEqual(expectedArray, ["one", "two"],
               "Arrays passed are not equal.");			
         });
      </script>
   </body>
</html>
You should see the following result −
Tests completed in 4 milliseconds.6 assertions of 6 passed, 0 failed.
TestSuite (6)Rerun2 msStrings passed are equal.@ 0 msStrings passed are not equal.@ 1 ms5 is less than 6@ 1 ms6 is not less than 5@ 1 msArrays passed are equal.@ 1 msArrays passed are not equal.@ 1 msSource:     at https://www.tutorialspoint.com/qunit/src/using_assertions.htm:12:16
TestSuite (6)Rerun2 msStrings passed are equal.@ 0 msStrings passed are not equal.@ 1 ms5 is less than 6@ 1 ms6 is not less than 5@ 1 msArrays passed are equal.@ 1 msArrays passed are not equal.@ 1 msSource:     at https://www.tutorialspoint.com/qunit/src/using_assertions.htm:12:16
Strings passed are equal.@ 0 msStrings passed are not equal.@ 1 ms5 is less than 6@ 1 ms6 is not less than 5@ 1 msArrays passed are equal.@ 1 msArrays passed are not equal.@ 1 ms
Strings passed are equal.@ 0 ms
Strings passed are not equal.@ 1 ms
5 is less than 6@ 1 ms
6 is not less than 5@ 1 ms
Arrays passed are equal.@ 1 ms
Arrays passed are not equal.@ 1 ms
Source:     at https://www.tutorialspoint.com/qunit/src/using_assertions.htm:12:16
This chapter explains the execution procedure of methods in QUnit, that states which method is called first and which one after that. Following is the execution procedure of the QUnit test API methods with an example.
<html>
   <head>
      <meta charset = "utf-8">
      <title>QUnit basic example</title>
      <link rel = "stylesheet" href = "https://code.jquery.com/qunit/qunit-1.22.0.css">
      <script src = "https://code.jquery.com/qunit/qunit-1.22.0.js"></script>
   </head>
   
   <body>
      <div id = "qunit"></div>
      <div id = "qunit-fixture"></div> 
      <script>
         QUnit.module( "Module A", {
            beforeEach: function( assert ) {
               assert.ok( true, "before test case" );
            }, afterEach: function( assert ) {
               assert.ok( true, "after test case" );
            }
         });
         
         QUnit.test( "test case 1", function( assert ) {
            assert.ok( true, "Module A: in test case 1" );
         });
         
         QUnit.test( "test case 2", function( assert ) {
            assert.ok( true, "Module A: in test case 2" );
         });
		 		 
         QUnit.module( "Module B" );		
         QUnit.test( "test case 1", function( assert ) {
            assert.ok( true, "Module B: in test case 1" );
         });
         
         QUnit.test( "test case 2", function( assert ) {
            assert.ok( true, "Module B: in test case 2" );
         });		 
      </script>
   </body>
</html>
You should see the following result −
Tests completed in 10 milliseconds.8 assertions of 8 passed, 0 failed.
Module A: test case 1 (3)Rerun1 msbefore test case@ 1 msModule A: in test case 1@ 1 msafter test case@ 1 msSource:     at https://www.tutorialspoint.com/qunit/src/execution_procedure.htm:19:16Module A: test case 2 (3)Rerun1 msbefore test case@ 0 msModule A: in test case 2@ 0 msafter test case@ 1 msSource:     at https://www.tutorialspoint.com/qunit/src/execution_procedure.htm:22:16Module B: test case 1 (1)Rerun0 msModule B: in test case 1@ 0 msSource:     at https://www.tutorialspoint.com/qunit/src/execution_procedure.htm:27:16Module B: test case 2 (1)Rerun0 msModule B: in test case 2@ 0 msSource:     at https://www.tutorialspoint.com/qunit/src/execution_procedure.htm:30:16
Module A: test case 1 (3)Rerun1 msbefore test case@ 1 msModule A: in test case 1@ 1 msafter test case@ 1 msSource:     at https://www.tutorialspoint.com/qunit/src/execution_procedure.htm:19:16
before test case@ 1 msModule A: in test case 1@ 1 msafter test case@ 1 ms
before test case@ 1 ms
Module A: in test case 1@ 1 ms
after test case@ 1 ms
Source:     at https://www.tutorialspoint.com/qunit/src/execution_procedure.htm:19:16
Module A: test case 2 (3)Rerun1 msbefore test case@ 0 msModule A: in test case 2@ 0 msafter test case@ 1 msSource:     at https://www.tutorialspoint.com/qunit/src/execution_procedure.htm:22:16
before test case@ 0 msModule A: in test case 2@ 0 msafter test case@ 1 ms
before test case@ 0 ms
Module A: in test case 2@ 0 ms
after test case@ 1 ms
Source:     at https://www.tutorialspoint.com/qunit/src/execution_procedure.htm:22:16
Module B: test case 1 (1)Rerun0 msModule B: in test case 1@ 0 msSource:     at https://www.tutorialspoint.com/qunit/src/execution_procedure.htm:27:16
Module B: in test case 1@ 0 ms
Module B: in test case 1@ 0 ms
Source:     at https://www.tutorialspoint.com/qunit/src/execution_procedure.htm:27:16
Module B: test case 2 (1)Rerun0 msModule B: in test case 2@ 0 msSource:     at https://www.tutorialspoint.com/qunit/src/execution_procedure.htm:30:16
Module B: in test case 2@ 0 ms
Module B: in test case 2@ 0 ms
Source:     at https://www.tutorialspoint.com/qunit/src/execution_procedure.htm:30:16
This is how the QUnit execution procedure is.
The module is used to group test cases.
The module is used to group test cases.
beforeEach() method executes for each test case however before executing the test case.
beforeEach() method executes for each test case however before executing the test case.
afterEach() method executes for each test case however after the execution of test case.
afterEach() method executes for each test case however after the execution of test case.
In between beforeEach() and afterEach() each test case executes.
In between beforeEach() and afterEach() each test case executes.
Calling QUnit.module() again, simply reset any beforeEach/afterEach functions defined by another module previously.
Calling QUnit.module() again, simply reset any beforeEach/afterEach functions defined by another module previously.
Sometimes it happens that our code is not ready and the test case written to test that method/code fails if run. QUnit.skip helps in this regards. A test method written using Skip method will not be executed. Let's see the Skip method in action.
<html>
   <head>
      <meta charset = "utf-8">
      <title>QUnit basic example</title>
      <link rel = "stylesheet" href = "https://code.jquery.com/qunit/qunit-1.22.0.css">
      <script src = "https://code.jquery.com/qunit/qunit-1.22.0.js"></script>
   </head>
   
   <body>
      <div id = "qunit"></div>
      <div id = "qunit-fixture"></div> 
      <script>
         QUnit.module( "Module A", {
            beforeEach: function( assert ) {
               assert.ok( true, "before test case" );
            }, afterEach: function( assert ) {
               assert.ok( true, "after test case" );
            }
         });
         
         QUnit.test( "test case 1", function( assert ) {
            assert.ok( true, "Module A: in test case 1" );
         });
         
         QUnit.skip( "test case 2", function( assert ) {
            assert.ok( true, "Module A: in test case 2" );
         });
		 		 
         QUnit.module( "Module B" );		
         QUnit.test( "test case 1", function( assert ) {
            assert.ok( true, "Module B: in test case 1" );
         });
         
         QUnit.skip( "test case 2", function( assert ) {
            assert.ok( true, "Module B: in test case 2" );
         });		 
      </script>
   </body>
</html>
You should see the following result −
Tests completed in 6 milliseconds.4 assertions of 4 passed, 0 failed.
Module A: test case 1 (3)Rerun1 msbefore test case@ 0 msModule A: in test case 1@ 0 msafter test case@ 0 msSource:     at https://www.tutorialspoint.com/qunit/src/skip_test.htm:19:16skippedModule A: test case 2 (0)RerunSource:     at https://www.tutorialspoint.com/qunit/src/skip_test.htm:22:16Module B: test case 1 (1)Rerun0 msModule B: in test case 1@ 0 msSource:     at https://www.tutorialspoint.com/qunit/src/skip_test.htm:27:16skippedModule B: test case 2 (0)RerunSource:     at https://www.tutorialspoint.com/qunit/src/skip_test.htm:30:16
Module A: test case 1 (3)Rerun1 msbefore test case@ 0 msModule A: in test case 1@ 0 msafter test case@ 0 msSource:     at https://www.tutorialspoint.com/qunit/src/skip_test.htm:19:16
before test case@ 0 msModule A: in test case 1@ 0 msafter test case@ 0 ms
before test case@ 0 ms
Module A: in test case 1@ 0 ms
after test case@ 0 ms
Source:     at https://www.tutorialspoint.com/qunit/src/skip_test.htm:19:16
skippedModule A: test case 2 (0)RerunSource:     at https://www.tutorialspoint.com/qunit/src/skip_test.htm:22:16
Source:     at https://www.tutorialspoint.com/qunit/src/skip_test.htm:22:16
Module B: test case 1 (1)Rerun0 msModule B: in test case 1@ 0 msSource:     at https://www.tutorialspoint.com/qunit/src/skip_test.htm:27:16
Module B: in test case 1@ 0 ms
Module B: in test case 1@ 0 ms
Source:     at https://www.tutorialspoint.com/qunit/src/skip_test.htm:27:16
skippedModule B: test case 2 (0)RerunSource:     at https://www.tutorialspoint.com/qunit/src/skip_test.htm:30:16
Source:     at https://www.tutorialspoint.com/qunit/src/skip_test.htm:30:16
Sometimes it happens that our code is not ready and the test case written to test that method/code fails, if run. QUnit.only helps in this regards. A test method written using only method will be executed while other tests will not run. If more than one only methods are specified, then only the first one will execute. Let's see only method in action.
<html>
   <head>
      <meta charset = "utf-8">
      <title>QUnit basic example</title>
      <link rel = "stylesheet" href = "https://code.jquery.com/qunit/qunit-1.22.0.css">
      <script src = "https://code.jquery.com/qunit/qunit-1.22.0.js"></script>
   </head>
   
   <body>
      <div id = "qunit"></div>
      <div id = "qunit-fixture"></div> 
      <script>
         QUnit.module( "Module A", {
            beforeEach: function( assert ) {
               assert.ok( true, "before test case" );
            }, afterEach: function( assert ) {
               assert.ok( true, "after test case" );
            }
         });
         
         QUnit.test( "test case 1", function( assert ) {
            assert.ok( true, "Module A: in test case 1" );
         });
         
         QUnit.only( "test case 2", function( assert ) {
            assert.ok( true, "Module A: in test case 2" );
         });
		      
         QUnit.test( "test case 3", function( assert ) {
            assert.ok( true, "Module A: in test case 3" );
         });
		 
         QUnit.test( "test case 4", function( assert ) {
            assert.ok( true, "Module A: in test case 4" );
         });	 
      </script>
   </body>
</html>
You should see the following result −
Tests completed in 2 milliseconds.3 assertions of 3 passed, 0 failed.
Module A: test case 1RerunModule A: test case 2 (3)Rerun1 msbefore test case@ 0 msModule A: in test case 2@ 1 msafter test case@ 1 msSource:     at https://www.tutorialspoint.com/qunit/src/only_test.htm:22:16
Module A: test case 1Rerun
Module A: test case 2 (3)Rerun1 msbefore test case@ 0 msModule A: in test case 2@ 1 msafter test case@ 1 msSource:     at https://www.tutorialspoint.com/qunit/src/only_test.htm:22:16
before test case@ 0 msModule A: in test case 2@ 1 msafter test case@ 1 ms
before test case@ 0 ms
Module A: in test case 2@ 1 ms
after test case@ 1 ms
Source:     at https://www.tutorialspoint.com/qunit/src/only_test.htm:22:16
For every asynchronous operation in QUnit.test() callback, use assert.async(), which returns a "done" function that should be called when the operation has completed. assert.async() accepts call counts as a parameter. The callback returned from assert.async() will throw an Error, if it is invoked more than the accepted call count, if provided. Each done() call adds up to the call count. After every call gets completed, the test is done.
<html>
   <head>
      <meta charset = "utf-8">
      <title>QUnit basic example</title>
      <link rel = "stylesheet" href = "https://code.jquery.com/qunit/qunit-1.22.0.css">
      <script src = "https://code.jquery.com/qunit/qunit-1.22.0.js"></script>
   </head>
   
   <body>
      <div id = "qunit"></div>
      <div id = "qunit-fixture"></div> 
      <script>
         QUnit.test( "multiple call test()", function( assert ) {
            var done = assert.async( 3 );
            
            setTimeout(function() {
               assert.ok( true, "first callback." );
               done();
            }, 500 );

            setTimeout(function() {
               assert.ok( true, "second callback." );
               done();
            }, 500 );

            setTimeout(function() {
               assert.ok( true, "third callback." );
               done();
            }, 500 );
         });		 
      </script>
   </body>
</html>
You should see the following result −
Tests completed in 531 milliseconds.3 assertions of 3 passed, 0 failed.
multiple call test() (3)Rerun529 msfirst callback.@ 504 mssecond callback.@ 505 msthird callback.@ 510 msSource:     at https://www.tutorialspoint.com/qunit/src/async_call.htm:12:16
multiple call test() (3)Rerun529 msfirst callback.@ 504 mssecond callback.@ 505 msthird callback.@ 510 msSource:     at https://www.tutorialspoint.com/qunit/src/async_call.htm:12:16
first callback.@ 504 mssecond callback.@ 505 msthird callback.@ 510 ms
first callback.@ 504 ms
second callback.@ 505 ms
third callback.@ 510 ms
Source:     at https://www.tutorialspoint.com/qunit/src/async_call.htm:12:16
We can use assert.expect() function to check the number of assertions made in the test. In the following example, we're expecting three assertions to be made in the test.
<html>
   <head>
      <meta charset = "utf-8">
      <title>QUnit basic example</title>
      <link rel = "stylesheet" href = "https://code.jquery.com/qunit/qunit-1.22.0.css">
      <script src = "https://code.jquery.com/qunit/qunit-1.22.0.js"></script>
   </head>
   
   <body>
      <div id = "qunit"></div>
      <div id = "qunit-fixture"></div> 
      <script>
         QUnit.test( "multiple call test()", function( assert ) {
            assert.expect( 3 );
            var done = assert.async( 3 );
            
            setTimeout(function() {
               assert.ok( true, "first callback." );
               done();
            }, 500 );

            setTimeout(function() {
               assert.ok( true, "second callback." );
               done();
            }, 500 );

            setTimeout(function() {
               assert.ok( true, "third callback." );
               done();
            }, 500 );
         });		 
      </script>
   </body>
</html>
You should see the following result −
Tests completed in 526 milliseconds.3 assertions of 3 passed, 0 failed.
multiple call test() (3)Rerun523 msfirst callback.@ 506 mssecond callback.@ 507 msthird callback.@ 507 msSource:     at https://www.tutorialspoint.com/qunit/src/expect_assertions.htm:12:16
multiple call test() (3)Rerun523 msfirst callback.@ 506 mssecond callback.@ 507 msthird callback.@ 507 msSource:     at https://www.tutorialspoint.com/qunit/src/expect_assertions.htm:12:16
first callback.@ 506 mssecond callback.@ 507 msthird callback.@ 507 ms
first callback.@ 506 ms
second callback.@ 507 ms
third callback.@ 507 ms
Source:     at https://www.tutorialspoint.com/qunit/src/expect_assertions.htm:12:16
When integrating QUnit into other tools like CI servers, these callbacks can be used as an API to read test results. Following is the execution procedure of the QUnit callback API method with an example.
<html>
   <head>
      <meta charset = "utf-8">
      <title>QUnit basic example</title>
      <link rel = "stylesheet" href = "https://code.jquery.com/qunit/qunit-1.22.0.css">
      <script src = "https://code.jquery.com/qunit/qunit-1.22.0.js"></script>
   </head>
   
   <body>
      <div id = "qunit"></div>
      <div id = "qunit-fixture"></div> 
      <script>
         //Register a callback to fire whenever a testsuite starts.
         QUnit.begin(function( details ) {
            var data = document.getElementById("console").innerHTML;
            document.getElementById("console").innerHTML = "<br/>" + 
               "QUnit.begin- Test Suite Begins " + "<br/>" + 
               "Total Test: " + details.totalTests;
         });

         //Register a callback to fire whenever a test suite ends.		 
         QUnit.done(function( details ) {
            var data = document.getElementById("console").innerHTML;
            document.getElementById("console").innerHTML = data + "<br/><br/>" + 
               "QUnit.done - Test Suite Finised" +  "<br/>" + "Total: " +  
               details.total + " Failed: " + details.failed + " Passed: 
               " + details.passed;
         });
		 
         //Register a callback to fire whenever a module starts.
            QUnit.moduleStart(function( details ) {
               var data = document.getElementById("console").innerHTML;
               document.getElementById("console").innerHTML = data + "<br/><br/>" + 
                  "QUnit.moduleStart - Module Begins " +  "<br/>" + details.name;
         });
		 
         //Register a callback to fire whenever a module ends.	  
         QUnit.moduleDone(function( details ) {
            var data = document.getElementById("console").innerHTML;
            document.getElementById("console").innerHTML = data + "<br/><br/>" + 
               "QUnit.moduleDone - Module Finished " +  "<br/>" + details.name + 
               " Failed/total: " + details.failed +"/" + details.total ;
         });
		 
         //Register a callback to fire whenever a test starts.
         QUnit.testStart(function( details ) {
            var data = document.getElementById("console").innerHTML;
            document.getElementById("console").innerHTML = data + "<br/><br/>" + 
               "QUnit.testStart - Test Begins " +  "<br/>" + details.module +" 
               " + details.name;
         });
		 
         //Register a callback to fire whenever a test ends.
         QUnit.testDone(function( details ) {
            var data = document.getElementById("console").innerHTML;
            document.getElementById("console").innerHTML = data + "<br/><br/>" + 
               "QUnit.testDone - Test Finished " +  "<br/>" + details.module +" " 
               + details.name + "Failed/total: " + details.failed +" " + details.total+ 
               " "+ details.duration;
         });
		 
         QUnit.module( "Module A", {
            beforeEach: function( assert ) {
               assert.ok( true, "before test case" );
            }, afterEach: function( assert ) {
               assert.ok( true, "after test case" );
            }
         });
         
         QUnit.test( "test case 1", function( assert ) {
            assert.ok( true, "Module A: in test case 1" );
         });
         
         QUnit.test( "test case 2", function( assert ) {
            assert.ok( true, "Module A: in test case 2" );
         });
		 		 
         QUnit.module( "Module B" );		
         QUnit.test( "test case 1", function( assert ) {
            assert.ok( true, "Module B: in test case 1" );
         });
         
         QUnit.test( "test case 2", function( assert ) {
            assert.ok( true, "Module B: in test case 2" );
         });	 
      </script>

      <div id = "console" ></div>
   </body>
</html>
You should see the following result −
Tests completed in 7 milliseconds.0 assertions of 1 passed, 1 failed.
global failure (1, 0, 1)Rerun1 msUncaught SyntaxError: Invalid or unexpected token@ 1 msSource: https://www.tutorialspoint.com/qunit/src/callbacks.htm:26Source:     at window.onerror (https://code.jquery.com/qunit/qunit-1.22.0.js:434:11)
global failure (1, 0, 1)Rerun1 msUncaught SyntaxError: Invalid or unexpected token@ 1 msSource: https://www.tutorialspoint.com/qunit/src/callbacks.htm:26Source:     at window.onerror (https://code.jquery.com/qunit/qunit-1.22.0.js:434:11)
Uncaught SyntaxError: Invalid or unexpected token@ 1 msSource: https://www.tutorialspoint.com/qunit/src/callbacks.htm:26
Uncaught SyntaxError: Invalid or unexpected token@ 1 msSource: https://www.tutorialspoint.com/qunit/src/callbacks.htm:26
https://www.tutorialspoint.com/qunit/src/callbacks.htm:26
Source:     at window.onerror (https://code.jquery.com/qunit/qunit-1.22.0.js:434:11)
Modules with grouped test functions are used to define nested modules. QUnit run tests on the parent module before going deep on the nested ones, even if they're declared first. The beforeEach and afterEach callbacks on a nested module call will stack in LIFO (Last In, First Out) Mode to the parent hooks. You can specify the code to run before and after each test using the argument and hooks.
Hooks can also be used to create properties that will be shared on the context of each test. Any additional properties on the hooks object will be added to that context. The hooks argument is optional if you call QUnit.module with a callback argument.
The module's callback is invoked having the context as the test environment, with the environment's properties copied to the module's tests, hooks, and nested modules.
<html>
   <head>
      <meta charset = "utf-8">
      <title>QUnit basic example</title>
      <link rel = "stylesheet" href = "https://code.jquery.com/qunit/qunit-1.22.0.css">
      <script src = "https://code.jquery.com/qunit/qunit-1.22.0.js"></script>
   </head>
   
   <body>
      <div id = "qunit"></div>
      <div id = "qunit-fixture"></div> 
      <script>
         QUnit.module( "parent module", function( hooks ) {
            hooks.beforeEach( function( assert ) {
               assert.ok( true, "beforeEach called" );
            });

            hooks.afterEach( function( assert ) {
               assert.ok( true, "afterEach called" );
            });

            QUnit.test( "hook test 1", function( assert ) {
               assert.expect( 2 );
            });

            QUnit.module( "nested hook module", function( hooks ) {
               // This will run after the parent module's beforeEach hook
               hooks.beforeEach( function( assert ) {
                  assert.ok( true, "nested beforeEach called" );
               });

               // This will run before the parent module's afterEach
               hooks.afterEach( function( assert ) {
                  assert.ok( true, "nested afterEach called" );
               });

               QUnit.test( "hook test 2", function( assert ) {
                  assert.expect( 4 );
               });
            });
         });
      </script>

      <div id = "console" ></div>
   </body>
</html>
You should see the following result −
Tests completed in 5 milliseconds.6 assertions of 6 passed, 0 failed.
parent module: hook test 1 (2)Rerun0 msbeforeEach called@ 0 msafterEach called@ 0 msSource:     at Object. (https://www.tutorialspoint.com/qunit/src/nested_modules.htm:21:19)parent module > nested hook module: hook test 2 (4)Rerun0 msbeforeEach called@ 0 msnested beforeEach called@ 0 msnested afterEach called@ 0 msafterEach called@ 0 msSource:     at Object. (https://www.tutorialspoint.com/qunit/src/nested_modules.htm:36:22)
parent module: hook test 1 (2)Rerun0 msbeforeEach called@ 0 msafterEach called@ 0 msSource:     at Object. (https://www.tutorialspoint.com/qunit/src/nested_modules.htm:21:19)
beforeEach called@ 0 msafterEach called@ 0 ms
beforeEach called@ 0 ms
afterEach called@ 0 ms
Source:     at Object. (https://www.tutorialspoint.com/qunit/src/nested_modules.htm:21:19)
parent module > nested hook module: hook test 2 (4)Rerun0 msbeforeEach called@ 0 msnested beforeEach called@ 0 msnested afterEach called@ 0 msafterEach called@ 0 msSource:     at Object. (https://www.tutorialspoint.com/qunit/src/nested_modules.htm:36:22)
beforeEach called@ 0 msnested beforeEach called@ 0 msnested afterEach called@ 0 msafterEach called@ 0 ms
beforeEach called@ 0 ms
nested beforeEach called@ 0 ms
nested afterEach called@ 0 ms
afterEach called@ 0 ms
Source:     at Object. (https://www.tutorialspoint.com/qunit/src/nested_modules.htm:36:22)
 Print
 Add Notes
 Bookmark this page