Overriding functions in other modules in node.js

时间秒杀一切 提交于 2019-12-04 12:44:16
f1nn

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

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

2) Pass parameters to a function

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.

Anatoliy

I've run into similar issue. After exploring request module code my solution was using request.get instead of request in my code (do exactly the same). And then stub it in test like that: https://github.com/anatoliychakkaev/resizer-app/blob/master/test/resizer.js#L25

It also possible to stub result of 'require' method in nodejs. Check sources on lib/module.js to manage how to do it. It should be something like:

require('module')._cache['/path/to/request.js'] = your_stub

But I don't like this solution because it doesn't work in 100% of cases and may stop working in future versions of node (this is not public api), so you should use this way only in case when it's not possible to use other ways of stubbing.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!