Reading Time: 4 minutes

 

Introduction

We’ve been using AngularJS at MuleSoft for building our upcoming web-based developer tools and so far we have really enjoyed using it. One area that’s really important to us as developers is unit testing our JavaScript code.This ensures we deliver high quality code that is easy to maintain and refactor and allows us to ship features quickly with confidence

Decorators in Angular are really useful for unit testing your Angular JavaScript code. This post is an example of how you can use them to to use them to create great unit tests.

latest report
Learn why we are the Leaders in API management and iPaaS

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 HelloWorld.

 

 

 

 

Testing 1,2,3

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 worldGreeter variable.

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.