我如何断言一个函数被调用?

我有一个山羊类:

class Goat constructor: (@headbutt) -> @isCranky = true approach: -> if @isCranky @headbutt() 

我想写一个摩卡testing来声明,如果isCranky为true并调用方法,则调用headbutt()。

我能find的唯一解释是在Ruby中。 试着翻译它,但失败了。 我怎样才能断言正确的function被称为? 我认为我可以用一种拙劣的方式解决问题,但宁可学习正确的方法。 build议?

怎么样?

 describe 'Goat', -> it 'should call headbutt when approached', -> headbuttCalled = no headbutt = -> headbuttCalled = true goat = new Goat headbutt goat.approach() assert headbuttCalled 

如果你发现自己多次重复这种testing函数是否被调用的模式,你可能会想使用像SinonJS这样的提供“间谍”构造的东西:

 headbutt = sinon.spy() goat = new Goat headbutt goat.approach() assert headbutt.called