QUnit allows you to test synchronous and asynchronous code. For the moment we’ll focus on testing synchronous code because it’s the easiest way to delve into the world of QUnit.
To create a test in QUnit you have to use a method called test(). Its syntax is shown here.
To create a new test, write the following code:
QUnit.test('My first test', function(assert) {
// Code here...
});
If you put this test in the previously mentioned tests.js file or inline it and then open the HTML file in a browser, you’ll see an error. The framework is complaining that you’ve defined a test without any assertion. What’s the sense of defining a test if you don’t test any code at all?
When creating a test, it’s a best practice to set the number of assertions you expect to be executed. This can be done by using the expect() method of the assert parameter described when discussing QUnit.test(). If you deal with synchronous code only, the use of expect() might seem useless because you might think that the only way an assertion could not be executed is if an error, caught by the framework, occurs. This objection is valid until you take into account asynchronous code. For the moment, trust us and use expect().
The syntax of expect() is as follows.
Method syntax: expect | |
---|---|
expect(total) | |
Set the number of assertions that are expected to run within a test. If the number of assertions actually executed doesn’t match the total parameter, the test will fail. | |
Parameters | |
total | (Number) The number of assertion expected to run within the test. |
Returns | |
undefined |
With the knowledge of the expect() method in hand, you can now modify the previous test to set your expectation of running zero tests:
QUnit.test('My first test', function(assert) {
assert.expect(0);
});
If you reopen the HTML page, you’ll find that the previous error message has disappeared. The reason is that with this change you’ve explicitly set the number of assertions to be executed to zero, so QUnit is sure that this is exactly what you wanted.
By using expect() you’ve fixed the issue in your HTML page but you still don’t have any assertions in place. Let’s examine the various types of assertions QUnit provides.
Leave a Reply