Sinon.spy 未调用某个方法

Sinon.spy on a method is not invoked

我正在测试的代码相当简单:它会在条件得到验证时调用一个方法。如果不是,它会调用包含在第一个方法中的另一个方法作为属性。

app.js:

function test (fn, isActivated) {
  if (isActivated) {
    return fn('foo')
  }

  return fn.subFn('bar')
}

var fn = function (p) { return p }
fn.subFn = function (p) { return 'sub-' + p }

var resFn = test(fn, true)
var resSubFn = test(fn, false)

document.write(resFn) // shows 'foo' as expected
document.write(resSubFn) // shows 'bar' as expected

我在每个方法上都设置了一个侦测器,但是在 fn 方法上的侦测器似乎不起作用,而在所包含的方法 subFn 上进行侦测器有效。见下文:

app.test.js:

'use strict'

const chai = require('chai')
const sinon = require('sinon')
const trigger = require('../app').trigger

chai.should()

describe('test app', function () {
    before(function () {
      this.fn = function () {}
      this.fn.subFn = function () {}
      this.subFnSpy = sinon.spy(this.fn, 'subFn')
      this.fnSpy = sinon.spy(this.fn)
    })

    describe('isActivated is true', function () {
      before(function () {
        trigger(this.fn, true)
      })

      it('should invoke fn', function () {
        this.fnSpy.callCount.should.equal(1) // return false because callCount = 0
      })
    })

    describe('isActivated is false', function () {
      before(function () {
        trigger(this.fn, false)
      })

      it('should invoke subFn', function () {
        this.subFnSpy.callCount.should.equal(1) // return false because callCount = 0
      })
    })
  })

我发现 fn 函数上的间谍有问题,我尝试了两种不同的方法。在这种情况下,两个间谍都失败了:

app.js:

exports.trigger = function (fn, subFn, isActivated) {
  if (isActivated) {
    return fn('fn')
  }

  return subFn('bar')
}

app.test.js

'use strict'

const chai = require('chai')
const sinon = require('sinon')
const trigger = require('../app').trigger

chai.should()

describe('test app', function () {
    before(function () {
      this.fn = function () {}
      this.subFn = function () {}
      this.fnSpy = sinon.spy(this.fn)
      this.subFnSpy = sinon.spy(this.subFn)
    })

    beforeEach(function () {
      this.fnSpy.reset()
      this.subFnSpy.reset()
    })

    describe('isActivated is true', function () {
      before(function () {
        trigger(this.fn, this.subFn, true)
      })

      it('should invoke fn if isActivated is true', function () {
        this.fnSpy.callCount.should.equal(1) // return false
      })
    })

    describe('isActivated is false', function () {
      before(function () {
        trigger(this.fn, this.subFn, false)
      })

      it('should invoke subFn if isActivated is true', function () {
        this.subFnSpy.callCount.should.equal(1) // return false
      })
    })
  })

有什么我做错的建议吗?

我没有找到确切的解决方案,但找到了一个非常接近的解决方法。所以问题似乎在于 this.fnsinon.spy 中的处理方式,而不是这样做:

this.fnSpy = sinon.spy(this.fn)
this.subFnSpy = sinon.spy(this.subFn)

我们执行以下操作:

this.fnSpy = sinon.spy(this, 'fn')
this.subFnSpy = sinon.spy(this.fn, 'subFn')

我使用 this 来存储 fnsubFn