2017-08-17 60 views
3

我正在使用Mocha和sinon间谍函数调用。该函数被正确调用,但间谍没有跟踪它。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,并没有注意到它正在监视的事情。我错过了什么吗?

回答

5

当您拨打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; 
})();