Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sinon spy function called but not tracked

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?

like image 289
Frazer Wilson Avatar asked Oct 22 '25 14:10

Frazer Wilson


1 Answers

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;
})();
like image 51
Louis Avatar answered Oct 24 '25 04:10

Louis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!