【问题标题】:How to stub a super() call with Sinon如何使用 Sinon 存根 super() 调用
【发布时间】:2013-05-15 10:01:47
【问题描述】:

我正在使用 Coffeescript,我正在使用 Sinon.js 进行测试。在测试调用它覆盖的方法的方法时,我如何存根对 super() 的调用?

例如,我要测试的方法(backbone.js 模型):

class Whatever extends Model
  validate: (attributes) ->
    validationErrors = super(attributes)
    ...
    validationErrors

在示例中,我想确保使用给定属性调用 super() 并且 validate 返回验证错误 super() 返回。

【问题讨论】:

    标签: coffeescript sinon


    【解决方案1】:

    像这样:

    it 'calls super and returns its result', ->
      whatever = new Whatever()
      attributes = sinon.stub()
      superValidateStub = sinon.mock(Whatever.__super__)
      superValidateStub.expects('validate').withExactArgs(attributes).returns('VALIDATION_RESULT')
    
      expect(whatever.validate(attributes)).to.eql('VALIDATION_RESULT')
    
      superValidateStub.verify()
    

    希望这对任何人都有帮助。

    【讨论】:

    • 不应该先模拟然后构造吗?
    • @AdrianLang:在这种情况下不需要,因为__super__Whatever 构造函数的属性,而不是它的原型。 Whatever.validate 中的 super 语句被转换为 Whatever.__super__.validate()
    猜你喜欢
    • 2017-05-04
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-13
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多