HTML and CSS Reference
In-Depth Information
13.1.3 Testing Timers
JsTestDriver does not do asynchronous tests, so we need some other way of test-
ing use of timers. There is basically two ways of working with timers. The ob-
vious approach is stubbing them as we have done with ajax.request and
ajax.create (or in a similar fashion). To stub them easily within tests, stub
the window object's setTimeout property, as seen in Listing 13.14.
Listing 13.14 Stubbing setTimeout
(function () {
TestCase("ExampleTestCase", {
setUp: function () {
this.setTimeout = window.setTimeout;
tearDown: function () {
window.setTimeout = this.setTimeout;
"test timer example": function () {
window.setTimeout = stubFn();
// Setup test
JsUnit, although not the most modern testing solution around (as discussed
in Chapter 3, Tools of the Trade ), does bring with it a few gems. One of these is
jsUnitMockTimeout.js , a simple library to aid testing of timers. Note that
although the file is named “mock,” the helpers it defines are more in line with what
we have been calling stubs.
jsUnitMockTimeout provides a Clock object and overrides the native
setTimeout , setInterval , clearTimeout , and clearInterval func-
tions. When Clock.tick(ms) is called, any function scheduled to run sometime
within the next ms number of milliseconds will be called. This allows the test to
effectively fast-forward time and verify that certain functions were called when
scheduled to.
The nice thing about the JsUnit clock implementation is that it makes tests focus
more clearly on the expected behavior rather than the actual implementation—do
some work, pass some time, and assert that some functions were called. Contrast
Search WWH ::

Custom Search