Writing unit test to check that event was triggered
I am wondering what is the correct approach. First here is the test code.
describe 'Something', ->
it 'should be triggering even', (done) ->
spy = sinon.spy()
instance = new Something()
instance.on("itsdone", spy)
instance.methodCall()
spy.should.have.been.calledOnce
done()
Looks pretty straightforward, but since events are usually asynchronous,
this cannot work.
class Something
constructor: ->
@events = {}
on: (event, cb) ->
@events[event] = new signals.Signal() unless @events[event]?
@events[event].add cb
methodCall: ->
# Fire up `itsdone` event when everything else is done
setTimeout (-> @events['itsdone']?.dispatch()), 0
I have figured out one way to do it...
describe 'Something', ->
it 'should be triggering even', (done) ->
instance = new Something()
instance.on("itsdone", done)
instance.methodCall()
This works correctly and when event is not triggered, test will fail after
2 seconds. However there is no verification, that it was triggered only
one. Maybe I need another test for that ? Since I already know it's
triggered at least once, I can use test with spy after this one probably.
Another "dirty" approach could be this:
This way test will fail obviously. Then I thought about something like
this...
describe 'Something', ->
it 'should be triggering even', (done) ->
spy = sinon.spy()
instance = new Something()
instance.on("itsdone", spy)
instance.methodCall()
setTimeout ->
spy.should.have.been.calledOnce
done()
, 0
This works too, but probably not really bulletproof. It would need bigger
timeout probably to be sure. However that means tests will take longer to
process, which is not good idea.
Do you have any other ideas how this should be solved ?
No comments:
Post a Comment