thlorenz / proxyquire

🔮 Proxies nodejs require in order to allow overriding dependencies during testing.
MIT License
2.75k stars 99 forks source link

Proxyquire running original dependency code #107

Closed tiagopadua-hp closed 8 years ago

tiagopadua-hp commented 8 years ago

Hello,

I'm not really sure if this is a problem or it's by design, but it's something causing me problems to write my unit tests. Also, I have not found any documentation nor posts about this in any forums (googled for hours).

Well, let's give an example. To simplify things, say my project has the following structure:

/a.js

var b = require('./b');
console.log(b);

/b.js

console.log('I dont want this to print out');
module.exports = 'B';

/tests/test.js

var proxyquire = require('proxyquire');

var a = proxyquire('../a', {
    './b': 'MOCKED'
});

// tests below...

I want to test the file a.js and mock its dependency (b.js).

But when I run the tests/test.js, the original file b.js is being executed, even when I mocked it with proxyquire. The result is the following:

$ node tests/test.js 
I dont want this to print out
MOCKED

In the project I got, instead of a console.log, the code of "b.js" actually connects automatically to a Redis server, and this is giving me troubles.

I tried to add , '@noCallThru': true but same result.

Is there any way to block the b.js from running at all?

bendrucker commented 8 years ago

Proxyquire will try to load the original module in order to fill the unstubbed keys. The way to prevent that is with the noCallThru feature. The string key with @ needs to be part of a module stub (e.g. './b', not the stub object itself. Instead, you can enable that feature like this:

https://github.com/thlorenz/proxyquire#all-together-now

You can't use the property shortcut because you're exporting a string from your module.