thlorenz / proxyquire

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

Problem when stubbing for just one test #254

Closed Coteh closed 4 years ago

Coteh commented 4 years ago

I am not sure what's happening, but when I try to use proxyquire for just one test and then restore the stub back for other tests, it does not seem to restore the property back to its original state. Even with proxyquire's default of calling thru to the original methods unless otherwise specified, it just doesn't seem to restore it. I'm not sure if there's something wrong with the require cache, or if I'm using proxyquire incorrectly. I have attached a runnable example of my problem here:

https://github.com/Coteh/proxyquire-problem

Simply clone, npm install, and npm start. You can see what I'm doing here.

I have tried

I have worked around this problem by requireing the original module in my test suite and explicitly setting the property in the stub object to the original function. However, I just thought I'd post this here to try to get some answers if possible. Let me know if this is more of a usage problem rather than an issue and I'll close it, thanks.

bendrucker commented 4 years ago

Hi, don't have too much time to pick this apart, but will try to give you some basic guidance. You can't just delete methods off a stub you already supplied. That stub has already overriden the specified module. It's not a dynamic system where whatever isn't in the stub falls through. Everything is resolved at the time you call proxyquire. So TypeError: childProcess.spawn is not a function is entirely expected. Appreciate the repro, output would also be helpful next time since this is easy enough to spot without even invoking the code.

Mutating stubs after calling proxyquire is never a good move, you should always call proxyquire again to get a new copy of the module under test with a new stub. Never share mutable state among tests if you can avoid it, that's not unique to proxyquire.

Briefly, more like this:

let a
beforeEach(function () {
  a = proxyquire('./a', stubs)
})

If the stubs change from test to test, proxyquire directly in the test function.