sinon icon indicating copy to clipboard operation
sinon copied to clipboard

Document how to do simple dependency injection

Open fatso83 opened this issue 7 years ago • 5 comments

There are usually three main categories of stubbing when dealing with network requests:

  1. stubbing out the api doing the actual network calls using a link seam
  2. stubbing out the api doing the actual network calls using dependency injection of some sort
  3. stubbing out the network layer in the underlying engine (browser or Node)

Presently we only have one article covering the first option, and very little on the two next approaches. We should create a small how-to for the article section that covers how to do basic (no framework) dependency injection.

I have already written a lot of text that could serve as the basis for such an article.

fatso83 avatar Jun 15 '17 08:06 fatso83

I think it could be nice to try and attack the same module using the three different approaches in three (inter-linked) articles so that user's could see how they compared. Maybe even putting sample code along with the tests in the repo so people could clone and run it as well. #foodforthought

fatso83 avatar Jun 15 '17 08:06 fatso83

Hi folks, I've used DI and Sinon together a bit in order to stub method dependencies. I would be willing to have a crack at this if it still needs doing.

Is this meant to be a doc on DI in general, or on using DI with Sinon to stub out dependencies?

FranceJ avatar Oct 06 '20 03:10 FranceJ

@FranceJ I'd be happy to have an article that showed how to do this using Sinon for the dependencies.

mroderick avatar Oct 06 '20 18:10 mroderick

Should this issue be closed, given there is a relevant documentation: https://sinonjs.org/how-to/stub-dependency/?

faithk7 avatar Oct 23 '22 23:10 faithk7

@faithk7 No, that is not using dependency injection. That is employing link seams / module level loader interception.

DI does not require any changes to the runtime. See the links I added at the top of this where I show how to allow substituting dependencies at runtime without any magic/additional complexity. This approach works regardless of using TypeScript, different JS runtimes (browser, Node, Deno) or transpiling to some other target level without needing to deep dive to get it working. Link seams are always dependant on the runtime, which means one approach used for Node will not work if transpiling using Webpack 3 which again will be different from Webpack 4, etc.

fatso83 avatar Oct 31 '22 10:10 fatso83