Let’s say, however, that right now, it’s just not appropriate – you’re writing something small, you’re writing something quickly, or you’re writing something before you have the chance to evaluate those technologies. Or maybe, like me… you’re just a lazy programmer. Look, I’m not going to judge – at least you’re testing your code, right?
Here’s an example of a function we want to test. It compares the fields on two objects, and if there are any differences, sends them to the server to be saved. For the purposes of testing, it would be super-convenient if we could just isolate our logic into functions responsible for –
- collecting all the differences between the two objects;
- starting a request to the server if those differences are not nil;
- making the XHR itself
Here’s how we’d write it without dependency injection:
Now let’s MacGyver a simple DI technique so we can test away:
_deps property is completely public, so it’s very simple for tests to manipulate it:
Now, this is not a scalable solution for big projects. Let me make that clear. It’s boilerplatey and it means making a compromise about encapsulation – that
_deps property is fully public, even if its leading underscore should hopefully indicate it’s not to be messed with. If you’re building something substantial, I would really invest my time in one of the solutions I linked to above. But for a very small project, it might well be less hassle than a full D.I. container, or getting Jest up and running.
Anyway, there you have it. A super-simple D.I. approach for super-simple applications. Let me know if you find it handy.