In my last blog post, I talked about “Test angular service using Karma and Jasmine”. Today I am going to talk about “Test angular controller using Karma and Jasmine”.
Testing Controller
Lets create a controller test file users.js and do as follows:
Let’s mock our angular module component.users using angular.mock in the following way:
To identify the controller users.js we need to add the dependency (inject) to our angular.mock.module in the following way:
Here we two undefined variable $controller and UsersController. Lets defined them:
Now lets start our first test case to check whether the controller is defined or not. To do so, follow this:
Now if we run the following command:
it will display error with controller
file name. To resolve this error lets create our controller file users.js
:
This time, you will see test case passed:
Testing Controller with Service Dependency
Let’s add the dependency user-service.js
(that we created in my last blog post) to the controller and write the test for that.
First modify users.spec.js
file as follows:
Now if you run # karma start
you will see an error, like that
To fix this error, modify users.js
controller by adding the service dependency:
This time you not see any more error.
Now lets define a method userService.all()
in service and try to access it in controller users.js
.
Update the controller test file users.spec.js
file:
This time if you run # karma start
, you will see an error like that:

To resolve this error we are going to use spyOn
method of Jasmine. Click here to know more about spyOn,
Now if you run # karma start
you will see the following error:

Let’s define the method in our user-service.js
file:
Now if you run # karma start
you will not see any error. Now add another Test Case like that:
That’s it. Now enjoy Testing your angular application.
Help:
– Testing AngularJS with Jasmine and Karma
– Jasmine SpyOn
Continue……
If you want to explore my playground, follow this github repository: https://github.com/masudiiuc/angular-unit-test