DEV Community

Discussion on: Why do I have to use Dependency Injection in JS?

Collapse
 
ld00d profile image
Brian Lampe

Did you know that Jest can mock your modules?

jestjs.io/docs/en/mock-functions.h...

Collapse
 
vyzaldysanchez profile image
Vyzaldy Andrés Sanchez

Hi Brian,

Yes, I do know Jest can achieve that but in my eyes that's kind of bit of magic... Having to import the direct modules installed via npm in the tests files and then override them with with another lib just doesn't feel right to me...

What about when I change that lib for some reason? I'm required to go to that file and change that by having lot of tests broken at that point, and I'll also have to change every module file in order to reflect the replacement which can be avoided using this approach. I prefer abstracting that responsibility of my modules and mocked them myself.

Hope this clarifies my point of view to you. Also, thank you for bringing the Jest fact here, so other guys knows there are already alternatives for this if they didn't know before.

Collapse
 
imthedeveloper profile image
ImTheDeveloper

Agree on the mocking. It feels dangerous to be faking npm modules to try and gain control of your test. Much simpler with injection and you aren't getting tied up in the mocking/unmocking workflows

Thread Thread
 
ld00d profile image
Brian Lampe

Isn't that the whole point though? You inject the npm modules with the sole purpose of mocking them. So in your unit test, you're not testing axios' connection to the web service, but via mocking, you can intercept those calls and stub a response for your unit test.