简体   繁体   English

如何使用jasmine-node监视节点模块中的私有函数?

[英]How do I spyOn private functions in a node module using jasmine-node?

app.js app.js

function _private() {
    console.log( '_private' );
}

function public() {
    console.log( 'public' );
    _private();
}

module.exports = {
    public: public,
    _private: _private
};

spec/appSpec.js 投机/ appSpec.js

describe( 'test', function() {
    it( 'will spy on _private', function() {
        var app = require( '../app' );
        spyOn( app, '_private' );
        app.public();
        expect( app._private ).toHaveBeenCalled();
    });
});

_private() is called, but the spy doesn't work and the test fails. 调用_private() ,但间谍不起作用,测试失败。

So as the question asks, how do I hook the spy up so that it knows that _private() was called? 所以当问题问,我如何挂钩间谍,以便它知道_private()被调用? Or is this not possible? 或者这不可能吗?

You can call _private with this otherwise the function is not defined. 您可以使用this方法调用_private ,否则函数未定义。 try this: 尝试这个:

function public() {
    console.log( 'public' );
    this._private();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM