3

I am currently testing a module in isolation using proxquire to overwrite a require of this module.

Overwriting a path of a require works fine with proxyquire. For example:

var bar = require('./bar');

But can you use proxyquire also to overwrite just a specific function of a module which is required in the module to test? So something like:

var bar = require('./foo').bar();

I need to stay at proxyquire for this since I am using it for mocking a http-request happening in another layer of the architecture. But in case of the test I need to mock the time for "now" in the module as well.

So currently I have this:

var uraStub = sendMockRequest(paramListOfCheckin, queryList);
var setNowStub = function(){ return 1425998221000; };

var checkin = proxyquire('../src/logic/logicHandlerModules/checkin', {
  '../../persistence/ura' : uraStub,
  './checkin.setNow' : setNowStub
});

checkin.checkin(...)

The implementation of setNow is:

var setNow = function(){
  return new Date().getTime();
};

var checkin = function (...) {
  var now = require('./checkin').setNow();

Obviousley './checkin.setNow' : setNowStub in proxyquire doesn't work, since this is the wrong path. But using './checkin'.setNow() : setNowStub also doesn't work because of wrong syntaxis in the object-definition.

Any suggestions?

Thanks in advance!

4

1 回答 1

0

您正在寻找的是 noCallThru() 和 callThru() 方法。https://github.com/thlorenz/proxyquire#preventing-call-thru-to-original-dependency

默认情况下,proxyRequire 将调用模拟依赖项,这将允许您选择要使用自己的自定义函数覆盖的方法。

因此,如果路径 '../foo' 中的依赖项具有方法 bar() 和 fooBar(),您将能够通过这样做来模拟 bar。

proxyquire.callThru();

var fooFunc = proxyquire('../foo', {
  bar: () => return 'bar'
})

现在 bar() 将命中您的自定义覆盖函数,而 fooBar() 将正常调用。

于 2021-12-13T22:01:04.987 回答