Keeping Tests Atomic - J Query

When tests are lumped together, it’s possible to have tests that should pass but fail or tests that should fail but pass. This is a result of a test having invalid results because of side effects of a previous test:

Notice the first append() adds a <span>that the second assert doesn’t take into account.


Use the test() method to keep tests atomic, being careful to keep each assertion clean of any possible side effects. You should only rely on the fixture markup, inside the #main element. Modifying and relying on anything else can have side effects:

QUnit will reset the elements inside the #main element after each test, removing any events that may have existed. As long as you use elements only within this fixture, you don’t have to manually clean up after your tests to keep them atomic.


In addition to the #main fixture element, QUnit will also clean up properties of jQuery itself: $ and $.ajaxSettings. Any global events like $().ajaxStart() are managed by jQuery in $—if your test had bound lots of them, it couldslow down the test runner significantly when running a lot of tests. By cleaning the property, QUnit ensures that your tests aren’t affected by global events.
The same applies to $.ajaxSettings, which is usually used via $.ajaxSetup() to configure common properties for $.ajax() calls.
In addition to the filters explained in Recipe (Selecting Tests to Run), QUnit also offers a ?noglobals flag.
Consider the following test:

In a normal test run, this passes as a valid result. Running the same test with the no globals flag will cause the test to fail, because QUnit detected that it polluted the window object.
There is no need to use this flag all the time, but it can be handy to detect global namespace pollution that may be problematic in combination with third-party libraries.
And it helps to detect bugs in tests caused by side effects.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

J Query Topics