Recently I have been involved in a discussion about let's just say modern JavaScript techniques. In the discussion a point was made about how difficult it is to perform dependency injection, which I completely disagree. Not only is JavaScript dependency injection (DI) relatively easy, JavaScript's dynamic nature makes it extremely easy to stub and mock objects and their members.
To me the harder part is writing or finding a library that is a testable mock, this is one of the strengths Angular has over other libraries, shipping with testible mock objects, at least that is what I have read. My favorite to actually test dependencies is with sinonjs, a mocking and stubbing library. Sinon does not do anything with dependency injection, instead it leverages JavaScript's dynamic nature and replaces dependencies with mocks, stubs and spies.
I tend to design my libraries with natural DI capabilities, which can be very handy if you do want to replace an entire object dependency. It is actually a product of designing my libraries to depend on an implied interface (remember JavaScript has no real interface concept) so I can swap out libraries later.
There are effectively 2 places I can inject a mock library when I design a module. Let me show with my SPA library’s code.
Your new post is loading...