Unit Testing an AngularJS Application

You need to install the following extension and framework:

  • Chutzpah VS Extension
  • Jasmine Test Framework

You can do this from Nu-Get Package,

  1. Go ahead and install Angular Js Core Nu-Get Package.

  2. Delete Sample Controller and Jasmine sample files.

  3. Create appcontroller.js in Controller Folder. And insert following code:
    1. angular.module('app', []).controller('appController', function ($scope) {  
    2. $scope.value = 5;  
  4. Create a Test folder and create appcontrollertest.js file. Inside that test file put the below code:
    1. describe('When using appController ', function()  
    2. {  
    3.     //initialize Angular  
    4.     beforeEach(module('app'));  
    5.     //parse out the scope for use in our unit tests.  
    6.     var scope;  
    7.     beforeEach(inject(function($controller, $rootScope)  
    8.     {  
    9.         scope = $rootScope.$new();  
    10.         var ctrl = $controller('appController',  
    11.         {  
    12.             $scope: scope  
    13.         });  
    14.     }));  
    15.     it('initial value is 5', function()  
    16.     {  
    17.         expect(scope.value).toBe(5);  
    18.     });  
    19. });  
    As you are using Jasmine framework, Describe is used to group the test cases together.

    It: Chutzpah will detect ‘it’ as a unit test. So use ‘it’ to create individual test case.

  5. Right Click on the test file and run the Unit test case.

You will get the result as pass or fail. Also you can run the test cases either on test explorer or browser also.

Ebook Download
View all
Learn
View all