QUnit is a powerful JavaScript unit testing framework. It can be used for testing jQuery, jQuery UI and jQuery Mobile projects, as well as any project written using JavaScript code.
Any Html and JavaScript editor (Visual Studio 2013)
Download reference js and css file
Add QUnit.js and QUnit.css to the HTML page you want to test.
<script src="//code.jquery.com/qunit/qunit-1.22.0.js"></script> <link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-1.22.0.css">
Put the code to be unit tested into a separate js file (Calculations.js):
// Create Calculation class. var Calculation = function () { }; // Add Addition to method to the Calculation class. Calculation.prototype.Add = function (a, b) { return a + b; }; // Add Subtraction method to the Calculation class. Calculation.prototype.Substraction = function (a, b) { return a - b; }; // Add Multiplication method to the Calculation class. Calculation.prototype.Multiplication = function (a, b) { return a * b; }; // Add pision method to the Calculation class. Calculation.prototype.pision = function (a, b) { return a / b; };
The following code is the unit test case for the above JavaScript method. We also put it in a separate js file (UnitTest.js):
// Instantiate Calculation class. var c = new Calculation(); // Unit test for addition. QUnit.test("Addition Test", function (assert) { assert.ok(c.Add(2, 3) == "5", "Passed!"); }); // Unit test for subtraction. QUnit.test("Substraction Test", function (assert) { assert.ok(c.Substraction(3, 2) == "1", "Passed!"); }); // Unit test for pision. QUnit.test("pision Test", function (assert) { assert.ok(c.pision(5, 5) == "1", "Passed!"); }); // Unit test for multiplication. QUnit.test("Multiplication Test", function (assert) { assert.ok(c.Multiplication(5, 5) == "25", "Passed!"); });
Create a p tag with the id of qunit and qunit-fixture in the HTML code.
<link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-1.22.0.css"> <script src="~/Scripts/Calculations.js"></script> <p id="qunit"></p> <p id="qunit-fixture"></p> <script src="//code.jquery.com/qunit/qunit-1.22.0.js"></script> <script src="~/Scripts/UnitTest.js"></script>
The above is the detailed content of Sample code details for JavaScript unit testing using QUnit. For more information, please follow other related articles on the PHP Chinese website!