我如何使 Sinon.JS callCount 递增

Phi*_*hil 2 javascript mocha.js sinon chai

所以我有一个这样的 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)
  })
})
Run Code Online (Sandbox Code Playgroud)

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

test me
[]
0
Run Code Online (Sandbox Code Playgroud)

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

rob*_*lep 5

如果您想监视常规函数,则可以跟踪对该函数的调用的唯一方法是调用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)
})
Run Code Online (Sandbox Code Playgroud)

如果testMe本来是对象(或类的方法)的属性,则可以调用原始版本,因为在这种情况下,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)
  })
})
Run Code Online (Sandbox Code Playgroud)