Sinon spy function called but not tracked

偶尔善良 提交于 2019-12-10 21:48:38

问题


I am using Mocha and sinon to spy on a function call. The function is called correctly but the spy is not tracking it.

Here is the module i am testing

export default (() => {

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

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

  return {
      test1,
      callThis
  };

})();

and here is the test

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

});

I am basically calling the first function but want to check the second function is called as a result. The console logs tell me this is happening, but the spy returns false and does not notice the thing it is spying on. Am i missing something?


回答1:


When you call sinon.spy(Common, 'test1'); you are modifying the test1 field on the Common object to replace it with a spy. However, the code you have in common.js is calling test1 directly instead of calling test1 through the object that your module exports. Therefore, when you do Common.callThis(), the spy is not touched, and you get the error you observed.

Here's a modified common.js file that would allow your test to pass:

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


来源:https://stackoverflow.com/questions/45732572/sinon-spy-function-called-but-not-tracked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!