覆盖 node.js 中其他模块中的函数 [英] Overriding functions in other modules in node.js

查看:49
本文介绍了覆盖 node.js 中其他模块中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Node.js 应用程序中使用 nodeunit 存根一个函数.这是我正在尝试做的简化版本:

I'm trying to stub a function with nodeunit in a Node.js app. Here's a simplified version of what I'm trying to do:

lib/file.js 中:

var request = require('request');

var myFunc = function(input, callback){
    request(input, function(err, body){
        callback(body);
    });
};

test/test.file.js中:

var file = require('../lib/file');

exports['test myFunc'] = function (test) {
    request = function(options, callback){
        callback('testbody');
    };

    file.myFunc('something', function(err, body){
        test.equal(body, 'testbody');
        test.done();
    });
};

似乎我没有正确覆盖 request,因为当我尝试运行测试时,实际的非存根 request 被调用,但我可以不知道正确的方法是什么.

It seems like I'm not overriding request properly, because when I try to run the test, the actual non-stub request is getting called, but I can't figure out what the correct way to do it is.

用我上面的例子来扩展下面 Ilya 的回答.

To expand on Ilya's answer below, with my example above.

lib/file/js中:

module.exports = function(requestParam){
    return {
        myFunc: function(input, callback){
            requestParam(input, function(err, body){
                callback(body);
            });
        }
    }
}

然后在test/test.file.js:

var fakeRequestFunc = function(input, callback){
// fake request function
}

var file = require('../lib/file')(fakeRequestFunc)(
//test stuff
}

推荐答案

正如您所注意到的,在一个模块中声明的变量不能轻易地从另一个模块访问.在这种情况下,您有两种常见的变体:

As you noticed, variables declared in one module, cannot easily be accessed from another module. In such cases, you have two common variants:

1) 在每个模块中声明你需要的一切(我想不是你的情况)

1) Declare everything you need in every module (not your case, I suppose)

2) 向函数传递参数

var ab = "foo",
index = require('/routes/index')(ab);

当您从模块中调用函数时,您可以向它传递请求"或您需要的任何其他变量或对象.

When you call a function form a module, you may pass it 'request' or any other vars or object you need.

这篇关于覆盖 node.js 中其他模块中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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