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!

Vegaaaa
  • 474
  • 4
  • 22

1 Answers1

0

What you are looking for is the noCallThru() and callThru() methods. https://github.com/thlorenz/proxyquire#preventing-call-thru-to-original-dependency

By default proxyRequire will call through to the mocked dependency which will allow you to pick the methods that you want to overwrite with your own custom function.

So if a dependency in the path '../foo' has a method bar() and fooBar() you would be able to mock out just bar by doing.

proxyquire.callThru();

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

Now bar() will hit your custom overwritten funtion while fooBar() will be called as normal.

Colin
  • 320
  • 2
  • 9