不调用方法上的Sinon.spy

时间:2016-01-14 17:27:04

标签: javascript unit-testing mocking sinon

我测试的代码非常简单:它会在条件得到验证的情况下调用方法。如果没有,它会调用第一个方法中包含的另一个方法作为属性。

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
      })
    })
  })

对我做错的任何建议?

1 个答案:

答案 0 :(得分:1)

我没有找到确切的解决方案,而是一个非常接近的解决方法。所以问题似乎在于使用this.fn处理sinon.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,因此很容易。