4

I am trying to use proxyquire to stub a require in a module that is required by a 3rd party module.

Example:

My module requires a 3rd mod called 'foo'.

That module depends on another library called 'bar' and in bar there is a require I want to mock. Is this possible?

in 3rd party lib called 'three':

  var bar = require('bar');

in bar lib:

  var thingiwanttomock = require('thingiwanttomock');

Then something like this in my test:

  it("test", function() {
    var mocked = proxyquire('thingiwanttomock', {});
  });

EDIT:

I think what I want is something like this:

var three = proxyquire('three', {
  'bar': {
    'thingiwanttomock': {
       'mocked': true 
     }
    }
  }
});

However if I put a console log in the bar library and print out what the thingiwanttomock variable is after the require, its not my mocked object.

in bar lib:

  var thingiwanttomock = require('thingiwanttomock');
  // this is not my object object
  console.log('thingiwanttomock should be a mock', thingiwanttomock);

Will proxyquire actually change what gets pulled in from a require statement in the dependent lib? Maybe that is where my confusion lies.

lostintranslation
  • 23,756
  • 50
  • 159
  • 262
  • What do you think about putting `var thingIwantToMock = require('thingiwanttomock');` in your test and than mock it from there? – Srle Jan 14 '16 at 00:47
  • The reason I am trying to avoid that is that I don't depend on thingiwanttomock so I cannot require it. I don't want to add that dependency just to test. I think this is something I can do with proxyquire. – lostintranslation Jan 14 '16 at 02:09
  • Were you able to resolve this? I am having the same issue and I do not want to put the 3rd party module in my test as Srle suggests. – sizzle Jan 25 '17 at 15:14

0 Answers0