如果间接调用间谍方法,则不调用Sinon Spy [英] Sinon Spy is not called if the spied method is called indirectly

查看:42
本文介绍了如果间接调用间谍方法,则不调用Sinon Spy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的代码库中,我们遇到了sinon的问题,可以使用下面的代码复制。问题是它似乎是间接的间谍返回力 false console.log 明确指出方法被调用,但 spy.called 仍为 false

In our codebase we have a problem with sinon which can be reproduced with the code snipped below. The thing is that it seems to be that indirect called spies return force false, the console.log clearly states that the method is called but the spy.called remains false.

以下CDN可用于html:

The following CDN's can be used for the html:

//cdnjs.cloudflare.com/ajax/libs/sinon.js/1.7.3/sinon-min.js
//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.14/require.min.js

main.js

require(['myModule'], function(module) {

    //using sinon
    var methodCallerSpy = sinon.spy(module, 'methodCaller')
    console.log(methodCallerSpy); // methodCaller
    module.methodCaller();
    console.log(methodCallerSpy.called); //true


    var methodSpy = sinon.spy(module, 'method');
    console.log(methodSpy); //method
    module.methodCaller();
    console.log(methodSpy.called); // false
    module.method();
    console.log(methodSpy.called); // true

});

模块

define(function() {
    const method = () => console.log('method called by methodCaller');

    const methodCaller = () => method();

    return{
        method,
        methodCaller
    }
});


推荐答案

问题在于 myModule 有两个名为 method() methodCaller()的私有函数以及两个方法它以相同的名称公开。

The problem is that myModule has two private functions called method() and methodCaller() as well as two methods it exposes with the same names.

Sinon能够监视公开的方法,但不能监视内部函数。

Sinon is capable on spying on the exposed methods, but not the internal functions.

当你打电话给 module.method()您调用公开的方法,因此Sinon能够检测到该调用。但是,当您调用 method.methodCaller()时, methodCaller()调用方法( )直接使用私有函数,因此Sinon不会检测到该调用。

When you call module.method() your invoking the exposed method, so Sinon is able to detect the call. However, when you call method.methodCaller(), methodCaller() calls the method() private function directly, and therefore the call is not detected by Sinon.

如果更改 methodCaller() 函数:

methodCaller = function(){
    this.method();
}

...然后Sinon应该能够捕获间接调用调用 methodCaller()时, method()

... then Sinon should be able to capture the "indirect" call to method() when calling methodCaller().

这篇关于如果间接调用间谍方法,则不调用Sinon Spy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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