
watching fun fun function today we’re
going to go through the basics of
dependency injection we are going to
talk about what dependency injection is
why it exists I’m going to show you how
to use it and finally I’m going to talk
about some caveats with it so what is
dependent injection let me show you with
some code let’s let’s imagine that we
have a function called get animal it
takes an ID it return it promise like
from a fetch if you don’t know what
fetches it’s a new function built into
modern browsers to do HTTP call I’m not
going to go into how it works but there
is an excellent video on the Google
developers channel that you can check
out here it’s not super important in
order to understand this video but in
case you were confused the response from
this imaginary API is Jason so we need
and the animals is probably in this
response somewhere so perhaps let’s say
that it’s it’s in date nook in some
results array like the first item in the
result array just imagine that so this
is a function that are uses the fetch
API to get some data analytics journal
service and it’s partly called Dustin
stuff without and it extracts the data
what you see here on screen does not use
dependency injection fetch here is
globally available in all over the place
in a browser fetch is actually just a
function on the window object so if we
wanted to be very specific about what is
happening we would type window dot fetch
like because window is a global variable
that you always have access to when you
are working in the browser for good and
evil you have to show you that I’m not
lying I’m going to open up a browser and
just do a link you see if I just stretch
here
I’ll see you yeah this fetch is a
function they decode and the arc it if
you do window dot fetch there it is it’s
always there it’s global now if this
function use dependency injection it
would probably look something like this
Oh anticlimactic I know
so now get animals has it dependency
injected it’s it’s getting a function
path to it called fetch that is the
function expects to treat your flight
you know the fetch idea so when you call
it get any moles you have to pass in the
function and the ID and then you do some
rendering I guess
that is dreadful code but you get the
point this is fundamentally all that
dependency injection is there’s no
libraries needed or there’s no framework
so it’s a piece of code that it needs
some dependency in this case fetch and
instead of that code being allowed to
you know conjure up that dependency
itself or access it wherever instead the
dependency is given to the code from the
outside like we do I could do here and
now you might be asking yourself why why
this extra step here why do we why don’t
we pass it in this this seems like just
extra work and there’s no clear benefit
well you could argue that dependency
injection may dependency is clearer
let’s for example say that we had like
four different things here not not only
fetched but also some database and blur
ability we dependency injection could
help expose that complexity rather than
if it was just called in the function
the the fact that get animals had too
many dependencies and was all over the
place would be more hidden that is a
little benefit of dependency injections
but the real reason that we do it is to
make the code testable I’m going to
comment this out here tulip and we are
going to write a unit test for for dead
save let me run the termokontroller
mocha no npm install’ g woke up if that
was confusing you’re new to JavaScript
mocha is a test runner for javascript
and i installed it here using the node
package manager which is a main deal of
package manager installed globally here
NPM is bundled with node which we’re
going to use in a bit which is yes the
JavaScript environment for the for the
command line for Prosperity I’m using
node version 7.4 you don’t need to
understand any of this to understand the
video but I’m just telling you so that
you know what’s going on so let me run
mocha and right no test focus looking
for as far as matching test I think I
had to just specify the file need to
couldn’t go to LOL bobba bobba desktop
and I’m going to run dude dot and I
calling this file episode J s don’t
describe it’s not defined always because
I’m trying to run it with low but we
want to run with with mocha the test
runner and so Jane yes ok cool now it
runs get animals works the basic case
these things described and it that you
see that it was not defined if we were
running it in a vanilla note environment
and that is because the mocha
environment magically summons these into
the global state that is why we have
access to them whatever let’s imagine
that this was not dependency injected
I’m going to remove this thing here and
we want to tap get animals are like one
two three the first thing that we want
to test is that the get animals function
actually cold stretch here like with
this you I like it uses the ID that we
pass in and gives it like shops it into
this this new endpoint here and then
cold fetch with it that is what we want
to test but now we have a problem
I let’s see I think we might see it if I
just run the test yes okay
fetch is not defined we’re running this
in node which is a CLI environment in a
browser this this would be defined we
want to replace fetch here with our own
fake or mock or stop the variance of the
fetch we once you have that like this
fetch here we want to intersect this
call but the problem is that seems get
animals itself is just grabbing this
from the global window object again
remember that this is this this is what
is actually happening we or the test
here like it doesn’t have any control
over what it doesn’t have any say of how
get animals called fetch the test
doesn’t have any way of getting into the
the get animal body so to speak it
cannot inspect what is what is going on
inside of it and this is the main reason
why dependency injection is used to
solve this problem so let me introduce
the dependence injection back and now we
are slowly getting into the how of
dependency injection so now get animals
requires a fetch method to be passed in
and now we want to assert that get
animals is calling fetch with this this
URI here so I’m going to paint that in
and like this this is the URI that we
want to call and we can check that with
by asserting that the Earle equals this
let’s try to run that we see that a
third is not defined and that is because
a third is something that is built into
no jab I’m going to just require that a
third require here’s the simple
assertion library built into no jazz and
worry about it what oh we get an error
because in on line 5 here it can’t read
property then of undefined
that is because fetch here it’s not
really returning returning a promise or
fake version here is just returning you
all nothing
so we need to fake a promise that never
returns I’m going to return promise and
then we just never call that result for
the moment and this will make work no
because I am not calling you let’s run
that again cool it works if you are
unfamiliar if you are unfamiliar with
promises I have an episode on that here
if you’re a Java developer they are
basically the same as futures so let’s
go through what we did here we
introduced fetch here as an argument to
get animals if we haven’t done that
fetch your calling or referencing fetch
it would be the same as referencing
window to fetch that is what happens and
if we do that there is no way
or get animals here to create a fake
fetch method and and inspect whatever
goes in to that and also fake the output
we have this argument here that we do
expect the fetch function and then we
create this fake better fetch function
here in the test and the fake bet
function works just like the real fetch
and it takes it takes an arrow and then
it asserts that the Earl equals what we
expect it to be and then just to make
sure that the test doesn’t break because
we are only interested in calling but
that it calls the and fetch with right
you are might actually rename the test
to that it calls the year called fetch
with the correct URI I open do this when
I’m unit setting by the way I’m often
well I often not exactly sure what the
what it is that I am testing so I often
get right like have to be
taught for instance for the first test
just to get myself going and then
usually the the purpose of the test
crystallizes itself like it did here let
me run the test again with the new
description it calls fetch with the
correct your eye this test is mainly
concerned with making sure that fake
fetch is being cold but then if you see
our fake fetch can also return values so
give me allow me to write one more test
to give you an idea of how it works when
we fake outputs from dependencies as
well part sets the response of fetch
correctly now let me delete this and
show you how I imagined our imaginary
animal form API animal
response to be because you see here I
just made this up it has a results
property results and that contains an
array of all the animals it is think
that they look something like you know
begins maybe it has a type for robot
robot robot dragon or or something we’re
just using our imaginations here but it
did is our imaginary API API response
okay I’m going to collapse this test for
now and let me say that okay let’s
create a new fake set fetch and we want
this to return a promise because the
fetch API is promise day and we want to
return a promise that with soul into an
object the response object that has of
stopped that has adjacent method and
that Jason method it’s our will when we
call it we want that we resolve into now
we wanted to return another promise that
resolves to data here and the little
iterative promise dot R is sold don’t
don’t
and this should basically a result to
this I’m going to copy that
out this is our fake data oh my god
indentation so hard if the parameters
freak you out compress the I icon in the
upper right corner to check out my video
on it I promise that promises are very
useful to you it no matter what
programming language you are coming from
them and there’s like so much knowledge
that will come out of learning them it
leads to funders it leads to monads and
all all so much good stuff but anyway we
had on straight fetch here and we’re
going to pass it into our get animals
and we are going to pass in fix it
cake fetch and we’re going to 1 2 3 4 5
and we expect it to return a promise
with and with Sol and we expect that
results the name T equal fluffy kin cool
let me just run that and feed break that
should not that should not task this is
an important unit testing technique
first thing that you want to do is get
read make sure that they break when they
should break so that you know that the
test is testing something since this is
an a synchronous test this is being
called later we need to use a done
function so that when we are done with
the test we we call we call done I’m
going to come down there right okay see
run it again okay it’s green I didn’t
really expect that but maybe I actually
wrote the code right let’s let’s let’s
check that by just breaking the code yes
oh wow it actually yes but it breaks
fantastic its next one so I I’m just
going to put that back and OH
run it again Green run it again green
run again green this is one of the big
benefits of unit testing it’s like you
can run your test over and over and
guess and like a hit of dopamine to your
brain every time really great let’s walk
through it what did we do we have this
yet animal function
in the second test here and we’re
passing in some our fake fetch that we
create up here and an ID and then we
make sure that is returns a promise that
resolves to a result and then we assert
that that result has a name which is
fluffykins
we essentially check that if the result
is this this this thing here that it’s
completely unnecessary for the test I
just added it to have some fun inside
the fake fetch here we are basically
just making a fake version of of this
here also note here that I in the in the
upper test or in the first test we were
concerned with the URI
as we check the URI we don’t bother to
do that in this fake fetch here because
you know we are we’re just concerned
with the studies policy attached
correctly so we don’t write a lot of
unnecessary test code in fact we don’t
we don’t even need the Earl there
because we never use it technically we
don’t even need to pass anything in here
because the test is not testing that but
I usually like to leave valid arguments
in like this instead of removing them
because we might add checks checks later
also tests or kind of documentation so
it’s just nice that the calls look like
somewhat real calls and this is
basically what a dependency injection is
I had put this little bit of code online
there’s a link in the episode
description that was a what why and how
I just want to talk about a little bit
of caveats with dependency injection the
main annoying thing with dependency
injection is that it requires you to
restructure your application to make it
testable and this will emotionally work
a lot of people it just feels a little
bit wrong that you should have to
restructure your app just to
detestable and the Tennessee injection
does require quite a bit of structuring
especially when you start having money
layers in your application there are
absolutely other alternative ways of
solving the problem of dependencies
inside of functions that we need to fake
the inputs and output of those
dependencies somehow but I think that
dependency injection as a pattern to
deal with this is remarkably straight
forward it is reasonably easy to
understand if you don’t you know go and
use some dependency injection framework
and libraries don’t fall into the trap
or building dependency injection
frameworks and shite just inject your
dependencies directly and it makes your
application very easy to test and it’s
applicable in pretty much every language
out there it’s a very well-documented
pattern it’s very unmagical and it works
that’s it we’ve talked about dependency
injection basics we have talked about
what it is injecting dependencies into
code instead of having just code
grabbing whatever dependencies they feel
like we have talked about why that it
does have some structural benefit but
it’s mainly to make it easy to unit test
your code and then we went through and
looked at how to do that in practice and
we talked about some caveats with it
that it does require some restructuring
of your code but it does have the
advantage of being pretty simple
straightforward and you know just works
and that is it you have you have just
watched an episode of fun fun function I
release me every Monday morning always
hundred GMT times do not miss that
episode because it might be amazing if
you’re forgetful you can turn on the
little notification bell next to the
subscribe button in the YouTube app or
you can follow me on twitter at MP Jamie
if you liked this episode you might like
this week’s Odom’s composition over
inheritance or you might like this video
which youtube’s machine learning and
have taped for you by the way look at
this amazing t-shirt it caps Schrodinger
I and mgj until next Monday morning thank you