Home > Web Front-end > JS Tutorial > Getting Started with QUnit

Getting Started with QUnit

Jennifer Aniston
Release: 2025-02-21 12:12:13
Original
632 people have browsed it

Getting Started with QUnit

Software testing is a process of evaluating software to detect the difference between the expected output and the actual output of a given input set. Testing, especially unit testing, should be an essential part of every developer's life. Unfortunately, many developers seem to be afraid of the activity. In JavaScript, we can choose from many frameworks to test our code base. For example, Mocha, Selenium, and QUnit. In this article, I will introduce you to QUnit. QUnit is a unit testing framework developed and maintained by the jQuery team, which is also behind projects such as jQuery and jQuery UI.

Key Points

  • QUnit is developed and maintained by the jQuery team and is a popular JavaScript unit testing framework for its ease of use and simplicity of setup.
  • To get started with QUnit, download the latest version of JavaScript and CSS files from the QUnit website and include them in your HTML file.
  • QUnit provides two ways to create new tests: QUnit.test() for synchronous code and QUnit.asyncTest() for asynchronous code. These tests contain assertions that verify that the code works as expected.
  • QUnit provides a variety of assertion methods including deepEqual(), equal(), notDeepEqual(), notEqual(), propEqual(), strictEqual(), notPropEqual(), notStrictEqual(), ok(), throws(),
  • ,
  • , expect() and
  • . Each method has its specific purpose and accepts certain parameters.

When creating tests with QUnit, the best practice is to set the number of assertions to be executed using the method. This helps ensure that all assertions are executed and if one or more assertions are not executed, the test will fail.

Settings QUnit One of the main reasons many developers use QUnit is its ease of use. Getting started with this framework is very simple and you can master the main concepts in a few hours. The first step to using QUnit is obviously to start by downloading it. There are several ways to do this: manually download from the website, use CDN, use Bower, or use npm. My advice is that you should not rely on CDN to test your code unless you are developing a simple live demo. So stick to other options. For this article, I don't want to set any prerequisites (read Bower and npm), so we'll take the first approach. Therefore, visit the QUnit website and download the latest version of the JavaScript file (named qunit-1.14.0.js) and the CSS file (named qunit-1.14.0.css). Put them in a folder where you will also create an index.html. In this file, we will place the HTML code displayed on the home page of the website, and I will repeat it below for convenience.
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>QUnit Example</title>
  <link rel="stylesheet" href="qunit-1.14.0.css">
</head>
<body>
  <div id="qunit"></div>
  <div id="qunit-fixture"></div>
  <🎜>
  <🎜>
</body>
</html>
Copy after login
Copy after login

As you can see, this code uses CDN to include CSS and JavaScript files. Therefore, you have to update the link to include the files you downloaded earlier. In the mark, you can see some <div> placed. The first one has qunit as its ID, used by the framework to display its user interface, where the test results are displayed. The second <div>, whose ID is qunit-fixture, should be used by you (the developer). This element allows developers to test code that adds, edits, or removes elements from the DOM without worrying about cleaning up the DOM after each test. If you put the element you created by your code in this <div>, QUnit will handle the reset for us. Finally, we include a tests.js file that represents the file containing the tests. My advice is to use files to store tests when working with real projects. In the live demo I created for this tutorial, I used JSBin and certainly did not allow uploading of files. So in the demo, you'll see that I've inlined the test code. Now that you understand what it means to tag each section, open the index.html page in your browser to see what happens. If all goes well, you should see a live demo interface as shown below, which is also provided as JSBin: QUnit example. At this stage, the only part of this interface that is relevant to us is the part that shows the time QUnit spends processing tests, the number of assertions defined, and the number of tests passed and failed. The above demonstration shows that we do not define any tests. Let's solve this problem.

How to create tests using QUnit

QUnit provides two ways to create new tests: QUnit.test() and QUnit.asyncTest(). The first one is used to test code running synchronously, while the second one is used to test asynchronous code. In this section, I will describe how to create tests for synchronous code. The signature of the QUnit.test() method is as follows:

QUnit.test(name, testFunction)
Copy after login
Copy after login

The first parameter name is a string that helps us identify the created tests. The second parameter testFunction is a function that contains the assertions the framework will execute. The framework passes a parameter to this function that exposes all QUnit's assertion methods. Convert this description to code, we can update the tests.js file with the following code:

QUnit.test('我的第一个测试', function(assert) {
   // 断言在这里...
});
Copy after login

This code creates a new test identified by the string "My First Test" and a function with an empty body. Adding tests without any assertions is of no use. To solve this problem, we must learn the assertion methods available in QUnit.

QUnit's assertion method

Assertions are at the heart of software testing. They allow us to verify that our code works as expected. In QUnit, we have many ways to verify these expectations. They can be accessed in tests by parameters of functions passed to the QUnit.test() method (in our previous example, assert). The following list summarizes the available methods, as well as their functions and signatures:

  • deepEqual(value, expected[, message]): A recursive strict comparison that works for all JavaScript types. If value and expected are the same in terms of properties and values, and have the same prototype, the assertion is passed;
  • equal(value, expected[, message]): The value equals expected parameter provided using non-strict comparison (==) verification.
  • notDeepEqual(value, expected[, message]): Same as deepEqual(), but tests inequality;
  • notEqual(value, expected[, message]): Same as equal(), but tests inequality;
  • propEqual(value, expected[, message]): Strict comparison of the properties and values ​​of an object. If all attributes and values ​​are the same, the assertion passes;
  • strictEqual(value, expected[, message]): Use strict comparison (===) verification to provide the value parameter equal to the expected;
  • notPropEqual(value, expected[, message]): Same as propEqual(), but tests inequality;
  • notStrictEqual(value, expected[, message]): Same as strictEqual(), but tests inequality;
  • ok(value[, message]): If the first parameter is a true value, the assertion passes;
  • throws(function[, expected][, message]): Test whether the callback throws an exception and optionally compare the thrown errors;

The parameters accepted by these methods are as follows:

  • value: The value returned by a function, method, or the value stored in a variable that must be verified;
  • expected: The value to be tested. For the throws() method, this can be <q cite="http://api.qunitjs.com/throws/">Error 对象(实例)、Error 函数(构造函数)、与字符串表示匹配(或部分匹配)的正则表达式或必须返回 true 以通过断言检查的回调函数</q>;
  • message: an optional string describing the assertion;
  • function: The function to be executed should return an Error;

Now that you have understood the methods and parameters available, it's time to check out some code. Instead of writing multiple tests for a single function, I try to reproduce a more realistic example. Anyway, the tests I will show you should not be considered a complete test suite, but they should give you a specific idea of ​​where to start. In order to write the mentioned tests, we need to define some code to test. In this case, I will define an object literal like this:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>QUnit Example</title>
  <link rel="stylesheet" href="qunit-1.14.0.css">
</head>
<body>
  <div id="qunit"></div>
  <div id="qunit-fixture"></div>
  <🎜>
  <🎜>
</body>
</html>
Copy after login
Copy after login

As you can see, we define an object literal with three functions: max(), isOdd(), and sortObj(). The first one accepts any number of parameters and returns the maximum value. isOdd() Take a number as its parameter and test if it is an odd number. sortObj() Accepts an array of objects, ideally there should be an attribute named timestamp and sorts them according to the value of this attribute. The possible test sets of these functions are as follows: (The lengthy test code example is omitted here because the word limit has been exceeded, but the principle is consistent with the previous description)

Set expectations

When creating a test, the best practice is to set the number of assertions we expect to execute. Doing so, if one or more assertions are not executed, the test will fail. The QUnit framework provides a expect() method for this purpose. This method is especially useful when dealing with asynchronous code, but it is best to use it when testing synchronous functions. The signature of the expect() method is as follows:

QUnit.test(name, testFunction)
Copy after login
Copy after login
The

where the assertionsNumber parameter specifies the expected number of assertions. (The example of updating the test code is also omitted here because the word limit has been exceeded, but the principle is consistent with the previous description)

QUnit Introduction Conclusion

In this tutorial, I introduce you to the magical world of testing, especially how to unit test JavaScript code using QUnit. We've seen how easy it is to set up the QUnit framework and what methods it provides to test synchronization functions. In addition, you have also learned the set of assertion functions provided by the framework for testing the code. Finally, I mentioned the importance of setting the number of assertions we expect to run and how to set them using the expect() method. I hope you enjoyed this post and you will consider integrating QUnit into your project. (The FAQs part is omitted here because the word limit has been exceeded)

The above is the detailed content of Getting Started with QUnit. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template