Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marty-wang/1392471 to your computer and use it in GitHub Desktop.
Save marty-wang/1392471 to your computer and use it in GitHub Desktop.
Use SinonJS and Mocha to test async function of multiple callbacks
should = require 'should'
sinon = require 'sinon'
myModule = {}
myModule.asyncMethod = (callback) ->
timeout = 1000
setTimeout (->
process.nextTick ->
callback null, {
number: 0
}
setTimeout (->
process.nextTick ->
callback null, {
number: 1
}
setTimeout (->
process.nextTick ->
callback null, {
number: 2
}
), timeout
), timeout
), timeout
describe 'my module', ->
describe '#asyncMethod', ->
it 'should call back 3 times with no error and an object data', (done) ->
spy = sinon.spy()
callback = sinon.spy()
clock = sinon.useFakeTimers()
myModule.asyncMethod (err, data) ->
callback err, data
if data.number is 2
done()
# assertions
spy.calledBefore(callback).should.be.true
callback.callCount.should.eql 3
call0 = callback.getCall 0
call0.calledWithExactly(null, {
number: 0
}).should.be.true
call1 = callback.getCall 1
call1.calledWithExactly(null, {
number: 1
}).should.be.true
call2 = callback.getCall 2
call2.calledWithExactly(null, {
number: 2
}).should.be.true
spy()
clock.tick 3100
clock.restore()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment