Welcome back to CodeYourCraft! Today, we're diving into the world of QUnit Modules with jQuery. Let's get started! 🎯
QUnit Modules are a way to organize your tests in jQuery. They help us write maintainable, scalable, and reusable test suites. 📝
To create a QUnit Module, first, include the necessary files:
<!DOCTYPE html>
<html>
<head>
<link src="https://code.jquery.com/qunit/qunit-2.15.1.css" />
<script src="https://code.jquery.com/qunit/qunit-2.15.1.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="my-module.js"></script>
</head>
<body>
<h1>My Test Suite</h1>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<script id="qunit-test-runner-scripts" src="my-module.test.js"></script>
</body>
</html>Here, my-module.js contains the jQuery functions we want to test, and my-module.test.js contains our test suite.
In the test suite file (my-module.test.js), we write our tests using the test() function and assertions like equal(), ok(), etc.
test("Testing My Function", function(assert) {
assert.equal(myFunction(1), 2, "My Function does not work correctly.");
});Here, myFunction is the function we're testing in my-module.js.
You can organize tests by creating separate files for different functionalities. For example:
my-module1.test.js for tests related to my-module1.jsmy-module2.test.js for tests related to my-module2.jsThis way, your test suite stays organized and manageable.
To load multiple QUnit modules, add them as dependencies in the test suite file (my-module.test.js).
require([ "my-module1", "my-module2" ], function() {
module("My Test Suite");
test("Testing My Function 1", function(assert) {
// Tests for my-module1.js
});
test("Testing My Function 2", function(assert) {
// Tests for my-module2.js
});
});Here, require() is used to load the modules.
Save all your files and open the HTML file in a web browser. QUnit will run your test suite automatically. ✅
What is the purpose of QUnit Modules?
Happy testing! 💡