Created
November 16, 2011 22:55
-
-
Save marty-wang/1371779 to your computer and use it in GitHub Desktop.
Use SinonJS to test async functions using process.nextTick
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
vows = require 'vows' | |
should = require 'should' | |
sinon = require 'sinon' | |
class FakeTicker | |
constructor: -> | |
@_originalTick = process.nextTick | |
sinon | |
.stub(process, 'nextTick', (callback)-> | |
setTimeout (-> | |
callback() | |
), 0 | |
) | |
@_clock = sinon.useFakeTimers() | |
tick: -> | |
@_clock.tick 100 | |
restore: -> | |
@_clock.restore() | |
process.nextTick = @_originalTick | |
unless sinon.useFakeTickers? | |
sinon.useFakeTickers = -> | |
new FakeTicker() | |
# ----------------------------------------------------------------------------- | |
asyncFunctionUnderTest = (callback)-> | |
process.nextTick -> | |
callback() | |
vows.describe('async function using next tick') | |
.addBatch( | |
'lines later should be executed before the async callback': -> | |
callbackSpy = sinon.spy() | |
testSpy = sinon.spy() | |
ticker = sinon.useFakeTickers() | |
asyncFunctionUnderTest callbackSpy | |
testSpy() | |
ticker.tick() | |
callbackSpy.calledOnce.should.be.true | |
testSpy.calledOnce.should.be.true | |
callbackSpy.calledAfter(testSpy).should.be.true | |
ticker.restore() | |
) | |
.export module |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment