Sinon间谍功能被召唤但未被追踪 [英] Sinon spy function called but not tracked

查看:119
本文介绍了Sinon间谍功能被召唤但未被追踪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是我正在测试的模块

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并且没有注意到它正在监视的事情。我错过了什么吗?

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?

推荐答案

当你打电话给 sinon.spy(Common,'test1'); 您正在修改 Common 对象上的 test1 字段,以将其替换为间谍。但是,您在 common.js 中的代码是直接调用 test1 而不是调用 test1 通过模块导出的对象。因此,当你执行 Common.callThis(),没有触及间谍,你得到了你观察到的错误。

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.

这是一个经过修改的 common.js 允许测试通过的文件:

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

这篇关于Sinon间谍功能被召唤但未被追踪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆