3 ms·
With JS, you can easily mock a whole module implementation so to use DI so that you can mock the injected entities during testing feels unnecessary.
by knuthsat 5y ago
With JS, you can easily mock a whole module implementation so to use DI so that you can mock the injected entities during testing feels unnecessary.
- eyelidlessness 5y agoI assume you’re referring to mocking like that provided by Jest? If so… I’ll add a two big caveats: 1. The mechanism used (clearing or overriding the cache) isn’t available for ESM, where mocking is significantly more challenging. 2. That mechanism is also responsible for a lot of memory leaks when any modules are stateful.
- postalrat 5y agoDoes bending your design to make it easier to mock result in better designs?
- eyelidlessness 5y ago1. It can promote simpler and easier to understand interfaces, but doesn’t guarantee it. 2. That doesn’t mean they’re “right” or necessarily “better”. 3. It depends a lot on the complexity of the code under test. If it’s really simple code—and especially if the stuff you intend to mock performs well and doesn’t mutate—making it easier to mock is probably going the wrong direction. 4. For most (>50%) things, yes. 5. But also for most things (off the cuff guess: >75%), you might be better off not mocking anyway. 6. If you (like me) prefer unit tests, you’ll probably get even better results by isolating as much of your code as possible from anything you’d want to mock in the first place.
- jitl 5y ago“Dependency injection”, especially this kind implementation, is fancy words for “calling your functions with commonly used parameters”. The language itself provides function parameters as part of the syntax of functions. Isn’t it easier and more clear to pass a dependency as a function parameter rather than mocking global state?
- bitwize 5y agoHave you ever worked in an enterprise environment? This kind of transformation happens all the time: <straightforward implementation> called <simple name> => <complicated implementation of same thing> called <fancy name> because <scalability, compliance, "best practice", or other BS reason>.
- lhorie 5y agoThe point is not so much how easy it is to mock, it's getting visibility into what should be mocked. Mocking moment.js with jest is relatively trivial, but your test is not going to warn you that your mock became inert if the implementation switched to date-fns. I've seen a number of occasions where a test using a mock passes one day then fails the next day because it turned out the mock was setup incorrectly, and the test was actually relying on wall clock, and it wasn't at all obvious that there was an issue because you could not statically analyze whether the mock was applied correctly.