Noglobals and notrycatch

QUnit offers you two check boxes, noglobals (labelled as “Check for Globals”) and notrycatch (labelled as “No try-catch”), that you can check and uncheck as needed in order to change the behavior of all tests performed on the page.

The noglobals flag will fail a test if a new global variable (which is the same as adding a property to the window object) is introduced by the code you’re executing. The following example shows a test that will fail if the noglobals flag is checked:

QUnit.test('Testing the noglobals option', function(assert) {
   assert.expect(1);
   window.appName = 'jQuery in Action';
   assert.strictEqual(appName, 'jQuery in Action', 'Strings are equal');
});

The reason the test fails is because the code added the appName property to the window object. The test wouldn’t have failed if the code had only modified an existing property of the window object such as name.

The notrycatch flag allows you to run QUnit without a surrounding try-catch block. This will prevent QUnit from catching any error and listing it, but often it allows for deeper debugging of an issue. The following example, which you can find in the file lesson-14/notrycatch.html, shows this option in action:

QUnit.test('Testing the notrycatch option', function(assert) {
   assert.expect(1);
   assert.strictEqual(add(2, 2), 4, 'The sum of 2 plus 2 is equal to 4');
});

In this code the add() function isn’t defined, so invoking it will cause an error (specifically a ReferenceError). If you run the code activating the notrycatch flag, the framework won’t catch this error for you and it’ll be logged in the console. The difference is shown in figures 14.3a and 14.3b.

Figure 14.3a. Executing the test without the notrycatch flag
Figure 14.3b. Executing the test with the notrycatch flag activated

When dealing with large applications, you need to keep your tests logically organized so that you’re able to run a specific group of tests without running the complete test suite. This is where modules come into play.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *