簡體   English   中英

Sinon間諜功能被召喚但未被追蹤

[英]Sinon spy function called but not tracked

我正在使用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(Common, 'test1'); 您正在修改Common對象上的test1字段以將其替換為間諜。 但是, 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;
})();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM