Testing Asynchronous Callbacks - J Query

Problem
While expect() is useful to test synchronous callbacks (see Recipe (Testing Synchronous Callbacks)), it falls short when testing asynchronous callbacks. Asynchronous callbacks conflict with the way the test runner queues and executes tests. When code under test starts a timeout or interval or an Ajax request, the test runner will just continue running the rest of the test, as well as other tests following it, instead of waiting for the result of the asynchronous operation.

Solution
There are two functions to manually synchronize the test runner with the asynchronous operation. Call stop() before any asynchronous operation, and call start() after all assertions are done, and the test runner can continue with other tests:

Discussion

A shortcoming of this approach to manual synchronization is the risk that start() is never called when the code under test fails elsewhere. In that case, the test runner never continues and therefore never finishes to display the end result. It can’t even display the result for the current test, so all that is displayed is the result of the previous test.
When that happens, you first need to identify the test that doesn’t finish by looking for the previous test that finished and then finding that test in code and skipping to the next test. Once that is done, you can ease debugging by adding a timeout argument to the call to stop():

In this example, the test runner would wait 500 ms for the test to finish (using set Timeout); otherwise, it would declare the test as failed and continue running. By seeing the result of other tests, it can be much easier to identify the actual problem and fix it.
Nonetheless, the timeout argument shouldn’t be used for regular tests. If you added it for debugging, remove it once the test works again.
Why is that? The drawback of the timeout is that it makes tests un deterministic. When running the test on a slow machine or under heavy load, the timeout may be too short, causing an otherwise perfectly fine test to fail. Hunting a bug that doesn’t exist at all is a very time-consuming and frustrating experience avoid it.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics