thlorenz / proxyquire

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

Stubbing another file that is required in an express route #249

Closed stephclleung closed 4 years ago

stephclleung commented 4 years ago

Hello, I'm using the following:

express.js chai sinon proxyquire

to test a route on my server. I can't seem to stub the files using proxyquire. Could you please point me to the right direction? The code belongs to my company and I have a repo with a very water downed version:

https://github.com/stephclleung/proxyquire-debug

Thank you very much.

bendrucker commented 4 years ago

Hi there, had a longer response that I closed mistakenly, sorry for the brevity as I try to re-type.

The problem you're having is that you require your app module first, and thereby load/cache it and all of its dependencies:

const server = require("../src/app.js")

When you later proxyquire('../src/router.js', {}), it's just creating a copy of the router module with stubs which you then don't use. Proxyquire cannot replace the reference to the router in an already loaded module, that's a fundamental Node limitation.

Instead you should always be proxyquire-ing your entry point, i.e.:

const server = proxyquire("../src/app.js", stubs)

If you need to mutate the router's deps too, make your stubbed router and then pass that as a stub to your app module:

const router = proxyquire("../src/router.js", stubs)
const server = proxyquire("../src/app.js", { './router.js': router })

Hope this helps!