I have a Goat class:
class Goat
constructor: (@headbutt) ->
@isCranky = true
approach: ->
if @isCranky
@headbutt()
I'd like to write a Mocha test to assert that headbutt() was called if isCranky is true and approach is called.
The only explanation I can find for this is in Ruby. Tried translating it, but failed. How can I assert that the correct function was called? I think I can solve it in a hacky way, but would rather learn the right way. Suggestions?
How about?
describe 'Goat', ->
it 'should call headbutt when approached', ->
headbuttCalled = no
headbutt = -> headbuttCalled = true
goat = new Goat headbutt
goat.approach()
assert headbuttCalled
If you find yourself repeating many times this pattern of testing whether a function was called, you'd probably want to use something like SinonJS, which provides a "spy" construct:
headbutt = sinon.spy()
goat = new Goat headbutt
goat.approach()
assert headbutt.called