如何使 Sinon.JS callCount 递增

How do I make Sinon.JS callCount increment

所以我有一个这样的 Chai/Mocha/Sinon 测试:

import sinon from 'sinon'

describe(`My Test`, () => {
  it(`should track the number of calls`, () => {
    function testMe() {
      console.log(`test me`)
    }
    const spy = sinon.spy(testMe)
    testMe()
    console.log(spy.getCalls())
    console.log(spy.callCount)
  })
})

测试运行时,会记录以下内容:

test me
[]
0

这令人费解。我做错了什么?

如果您想监视常规函数,跟踪对该函数的调用的唯一方法是调用 spy:

it(`should track the number of calls`, () => {
  function testMe() {
    console.log(`test me`)
  }
  const spy = sinon.spy(testMe)
  spy()
  console.log(spy.getCalls())
  console.log(spy.callCount)
})

如果testMe是一个对象的属性(或class的一个方法),你可以调用原来的方法,因为在那种情况下Sinon可以替换原始版本与间谍版本。例如:

describe(`My Test`, () => {
  it(`should track the number of calls`, () => {
    const obj = {
      testMe() {
        console.log(`test me`)
      }
    };
    const spy = sinon.spy(obj, 'testMe')
    obj.testMe();
    console.log(spy.callCount)
  })
})