First, we will start by defining two factories, one called
greeter and the other called
worldGreeter. What we want to achieve here is writing unit tests for the
worldGreeter factory instance.
Let’s start with a module named
myApp that contains both factories:
As you can see,
worldGreeter is simply concatenating the input from greeter. So, when injecting
worldGreeter the result will be the string
The testing frameworks we will be using are mocha as runner and chai for assertions. So let’s write the test:
We will replace
greeter with our own implementation. The additional injected parameter named
$delegate is a reference to the old
greeter instance. It is really helpful if you plan to use them with a mocking or stubbing framework like sinon.
Next, we are going to use another angular trick. We name the instance to be injected
_worldGreetereter_ so we can have a
worldGreeter instance on the describe scope. inject recognizes this and injects the proper instance allowing the usage of the more handy
Finally, we write an assertion to verify that
greeter was replaced successfully:
The bottom line
To sum up, great things can be achieved by using decorator in tests as it is really useful when having to replace instance dependencies. Last but not least, you can see the code working in this jsfiddle.