Stubbed out timer objects for testing
If you're writing a library which uses timers (like node-browserchannel), its annoying to wait 30 seconds for your timeout event to fire.
npm install timerstub
Add it to your package.json:
Timer stub provides a replacement version of
Date.now (through a wrapped
Instead of needing to spend real time waiting for your queued methods to be
called, you can now just call
timerstub.wait 1000, -> done() to 'wait' 1000
milliseconds. Any queued intervals and timeouts will be called (in order)
before your callback is called. Oh yeah, and
Date.now() will return the
right values in all the callbacks. As far as your library is concerned, 1000
milliseconds have really passed. But your test runs as fast as your CPU can
In your library, write something like this:
setIntervalclearIntervalsetTimeoutclearTimeoutDate=stubs# Write the rest of your code as normal.= ->timer = setTimeout -> foo1000start =time = DatenowclearTimeout timer# ...
In a testing framework like mocha:
timerstub = require 'timerstub'assert = require 'assert'mycoollibrary = require './mycoollibrary'mycoollibrarysetTimeFunctions timerstubdescribe 'my cool thing'beforeEach ->timerstubclearAll # This removes all queued timeouts and whatnotit 'does cool stuff':mycoollibrarycoolstufftimerstubwait 1000-># Now 1000 milliseconds of setInterval calls and stuff have run... instantly!assertstrictEqual yousexytruedone
In a parallel testing framework like expresso, simply add a call to
timerstub.wait(100000000) after all your tests have been scheduled. (In
expresso, that would be in a
testtimers should be compatible with all the testing frameworks - it doesn't interfere with the testing framework at all.
Licensed under the standard MIT license:
Copyright 2011 Joseph Gentle.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.