Unit Testing a Simple Controller in AngularJs

Tuesday, August 12, 2014

Introduction

This is part of a series of post related to how to set up and execute unit testing in AngularJs.

In this post, I will show an example of unit testing a simple controller.

In this case I have a started building a controller, and one of the first things I want to test is a collapsible panel inside my view. The way the panel works is when at first the user initially goes to view that has a list of items, at the top of the view there is a button that opens and closes a panel that contains a search text box so the user can filter the items on the page.


The Controller Code

So to start out, my new controller looks like this:

 

The $scope initially sets the isSearchCollapsed property to true, in which the view uses to indicate the panel is closed.

Here is the Jade view that shows or hides the panel.

 

Using the Angular UI directive, the panel slides open and closed based on the value of the isSearchCollapsed property. The value of that property is change every time the toggleSearchCollapsed is executed.


The Test Code

To test the controller code, I need to be able to replicate the controller and its scope in the test environment and Angular gives us a way to do that with two built in functions. Lets look at the code

First thing I need to do is to replicate the controller's scope so I can then attach it to the replicated controller. The $rootScope object has a function called $new which will do that for me. This function basically is used to create child scopes from the base scope.

The next thing I need to do is replicate the controller assigning our newly created scope to that controller. Angular uses the $controller service internally to instantiate controllers, and we can use it to instantiate our controller in our test environment.

Once that is set up we are ready to start testing, and in this case, I have three tests.

  • Starting from scratch my first test is there just to make sure I have successfully replicated the controller and it's scope.
  • The second test, makes sure the isSearchCollapsed property is initially set to false.
  • The third test, validates that when the toggleSearchCollapsed is triggered that the value of the isSearchCollapsed is changed. Since my second test passed and I know the initial value will be true, when I call the function and test the value again it should be false.

comments powered by Disqus