Skip to content

Instantly share code, notes, and snippets.

@marty-wang
Created November 16, 2011 22:55
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marty-wang/1371779 to your computer and use it in GitHub Desktop.
Save marty-wang/1371779 to your computer and use it in GitHub Desktop.
Use SinonJS to test async functions using process.nextTick
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