Javascript 已调用Sinon spy函数,但未跟踪

Javascript 已调用Sinon spy函数,但未跟踪,javascript,mocha.js,sinon,Javascript,Mocha.js,Sinon,我正在使用Mocha和sinon监视函数调用。函数调用正确,但间谍没有跟踪它 这是我正在测试的模块 export default (() => { function test1(){ console.log('called second func'); return 5; } function callThis(){ console.log('called first func'); test1(); } retur

我正在使用Mocha和sinon监视函数调用。函数调用正确,但间谍没有跟踪它

这是我正在测试的模块

export default (() => {

  function test1(){
      console.log('called second func');
      return 5;
  }

  function callThis(){
      console.log('called first func');
      test1();
  }

  return {
      test1,
      callThis
  };

})();
这是测试

import Common from './common';

describe('spy test', () => {
  var setSpy = sinon.spy(Common, 'test1');

  Common.callThis();

  var result = setSpy.called;

  it(`does the test`, () => {
      expect(result).to.equal(true);
  });

});

我基本上是在调用第一个函数,但是我想检查第二个函数是否被调用。控制台日志告诉我这正在发生,但是间谍返回false,并且没有注意到它正在监视的东西。我遗漏了什么吗?

当你调用
sinon.spy(常见的“test1”)
您正在修改
Common
对象上的
test1
字段,以将其替换为spy。但是,
common.js
中的代码直接调用
test1
,而不是通过模块导出的对象调用
test1
。因此,当您执行
Common.callThis()
时,间谍不会被触动,您会得到您观察到的错误

下面是一个经过修改的
common.js
文件,它允许您的测试通过:

export default (() => {

  var obj = {};

  obj.test1 = function test1(){
      console.log('called second func');
      return 5;
  }

  obj.callThis = function callThis(){
      console.log('called first func');
      // This calls `test1` through `obj` instead of calling it directly.
      obj.test1();
  }

  return obj;
})();