Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Tham khảo tài liệu 'phát triển javascript - part 34', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | 13.1 Polling for Data 303 13.1.3 Testing Timers JsTestDriver does not do asynchronous tests so we need some other way of testing use of timers. There is basically two ways of working with timers. The obvious 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 assert window.setTimeout.called 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 functions. 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 Download from www.eBookTM.com 304 Streaming Data with Ajax and Comet this to the usual stubbing approach in which we stub the timer do some work and then assert that the stub was used as expected. Stubbing yields shorter tests but using the clock yields more communicative tests. We will use the clock to test the poller to get a feel of the difference. The .