AngularJS has grown to become one of the most popular open-source web application frameworks, developed by a dedicated team at Google to address the challenges encountered in developing single-page-applications.

One of the reasons for AngularJS’ success is its outstanding ability to be tested. Most of the resources available at the time of writing for unit testing with Angular is well supported by Jasmine, a behavior driven development framework for testing JavaScript code.

Sample code for unit testing with jasmine:

blog1

Output:

 

blog6

In the above example we come across suite, specs and predefined matchers. Let’s have a look at it.

Suites and specs:

A Suite represents a bunch of tests that are related. Each suite in turn contains a set of Expectations that compare the results of the test with the actual and the expected value.

  • A Suite is defined by calling the describe()
  • It takes two parameters: the name of the Suite, and the function which contains the calls to the expectation methods called Specs.

Specs are defined using the it() method. It also takes two parameters like describe(),a name and function parameter. The it() function parameter may contain variables and one or more calls to the expect() method which is used in conjunction with a Matcher function, for comparing the actual and expected values.

Predefined matchers:

In the above example, the toEqual() method is a matcher. It represents the regular equality (==) operator.

Testing controllers:

As controllers are not available on the global scope, we use angular.mock.inject to inject our controller first. Then we pass module information into beforeEach, a function where Jasmine lets us run code before each test. Then we can use inject to access $controller the service that is responsible for instantiating controllers.

blog3

Output:

blog4

Testing filters:

blog5

Filters in angularjs are used to format the data.

Output:

blog6

Conclusion:

Unit testing becomes tricky at times, but it is worth spending the time on it as it ensures the correctness of the application. AngularJS makes it easier to unit test the code written using the framework.

I would like to hear your thoughts , Feel free to leave comments.

Have a great day!

Poojitha Gona

Angular Developer

Leave a Reply

Your email address will not be published. Required fields are marked *