mercredi 4 mai 2016

AngularJS : How to write unit test of controller

Pardon me If I am repeating this question. I am very new to AngularJS and Unit test cases with jasmine. I have started playing with angularJs very recently. I have gone through so many articles but I couldn't get any help. I want to write Jasmine unit test case for the below controller.

intelApp.controller('healthIndexCtrl', [ '$scope','$http','$filter','deviceService', '$controller','$localStorage','getSensorDetails', function ($scope,$http,$filter,deviceService,$controller,$localStorage,getSensorDetails) {
        //device variable declaration
        $scope.device = {
                        status : 'OFF',
                        statusColor : 'red',
                        id : '',
                        parameterValues : [],
                        trendChart : {
                        currentChartData : ''
                        }
                  };
        $scope.markers = [];
        $scope.devices=[];
        $scope.sensorData=[];
        $scope.isAnamolies='';
        $scope.pagination=true;
        $scope.tab2Show=false;
        //====================================Map functions==================================
        
        var mapOptions = {
                zoom: 4,
                center: new google.maps.LatLng(21.0000, 78.0000),
                mapTypeId: google.maps.MapTypeId.TERRAIN
            }
            $scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
           var infoWindow = new google.maps.InfoWindow();
         
        var createMarker = function (info) {
           
           //set image depends on status
           var markerIcon='';
           if(info.status=='Green'){
                        markerIcon='assets/images/green-dot.png';
           }else if(info.status=='Yellow')
           {
                        markerIcon='assets/images/yellow-dot.png'
           }
           else{
                markerIcon='assets/images/red-dot.png';
           }
           
       var marker = new google.maps.Marker({
                map: $scope.map,
            position: new google.maps.LatLng( info.latitude,  info.longitude),
                        icon:markerIcon,
            title: info.city,
            Name:info.name
        });
       
       google.maps.event.addListener(marker, 'mouseover', function () {
           infoWindow.setContent('<h4>Device Information</h4>Device Name : ' + marker.Name +'<br>DeviceType : ' +info.deviceType + '<br>Description : '+info.deviceDesc);
           infoWindow.open($scope.map, marker);
           $scope.information=true;
       });
           
           google.maps.event.addListener(marker, 'click', function () {
                        $scope.trendchart(info.name);
           });
           
            google.maps.event.addListener(marker, 'mouseout', function () {
                        infoWindow.close();
           });
            
                $scope.markers.push(marker);
                
    }
        
        $scope.openInfoWindow = function (e, selectedMarker) {
        e.preventDefault();
        google.maps.event.trigger(selectedMarker, 'click');
    }
                
        $scope.clearMarkers = function() {
              for (var i = 0; i < $scope.markers.length; i++) {
                $scope.markers[i].setMap(null);
              }
              $scope.markers.length = 0;
            }
        $scope.zoomToIncludeMarkers = function() {
            var bounds = new google.maps.LatLngBounds();
                console.log($scope.devices);
              $scope.devices.forEach(function(device) {
                 var latLng = new google.maps.LatLng(device.latitude,device.longitude);
                 bounds.extend(latLng);
        });
           
          $scope.map.fitBounds(bounds);
     }
        
          $("#mapCanvas").on('shown.bs.tab', function() {
                  $scope.tab2Show=false;
                  google.maps.event.trigger(map, 'resize');
                  $scope.zoomToIncludeMarkers();
                  $scope.$apply();
                  });
          
            $("#deviceList").on('shown.bs.tab', function() {
                  $scope.tab2Show=false;
                  $("#mytable tr").removeClass('selected');
                 $scope.$apply();
                  });
          
         //=============================Map ends here======================================
        

        /**
         * $on function gives the filtered devices on healthindex page
         */
        $scope.$on('passListToHealthIndex', function( event , obj){
                $scope.deviceListShow=true;
            $scope.pagination=obj.devices.length>0?false:true;
            $scope.tab2Show=false;
            $scope.warningShow=false;
            $scope.devices = obj.devices;
                console.log($scope.devices);
            //Plot marker for maps
                  for(i=0;i<$scope.devices.length;i++){
                        createMarker($scope.devices[i]);
                        $scope.zoomToIncludeMarkers();
                 }
            
            //Pagination settings
            $scope.viewby = 5;
                $scope.totalItems = $scope.devices.length;
                $scope.currentPage = 1;
                $scope.itemsPerPage = $scope.viewby;
                $scope.maxSize = 2; // Number of pager buttons to show          
                $scope.setPage = function (pageNo) {$scope.currentPage = pageNo;  };
                $scope.pageChanged = function() {
                 };
                  $scope.setItemsPerPage = function(num) {
                          $scope.itemsPerPage = num;
                          $scope.currentPage = 1; // reset to first paghe
                  }
        });
        
        
        //===============================Trend Chart ==============================
        //Function gets the sensor details, displays and visualize trend data in the line chart form 
        $scope.trendchart=function(deviceName){
                   for(var cnt=0;cnt<$scope.devices.id;cnt++){
                        try{
                        document.getElementById('trendChart'+cnt).innerHTML= '&nbsp;';
                        }catch(e){
                        }
                  }
                           $("#mytable tr").click(function(){
                                   $(this).addClass('selected').siblings().removeClass('selected');    
                                   var value=$(this).find('td:first').html();    
                                 });

                           $('.ok').on('click', function(e){
                                    alert($("#table tr.selected td:first").html());
                                 });
                                 
                                 
                           
        /**
         * @HTTP GET to get sensor details
         * @param deviceName 
         *@returns sensor details
         */
                
                getSensorDetails.query({vending_machine_id:deviceName},function(RESPONSE){
                        $scope.sensorData=RESPONSE.data;
                        $scope.device.parameterValues = $scope.sensorData.sensors;
                        
                        $scope.tab2Show=$scope.device.parameterValues.length>0?true:false;
                                
                        var temp=$filter('filter')($scope.devices, {deviceId:deviceName})[0];
                        $scope.isAnamolies=temp.status;
                        
                        if($scope.isAnamolies=='Yellow'){
                                $scope.warningShow=true;
                        }else{
                                $scope.warningShow=false;
                        }
                        
                        $scope.$apply();
                        //Draw trendchart for each sensors
                        for(var i=0;i<$scope.sensorData.sensors.length;i++){
                                drawTrendChart($scope.sensorData.sensors[i],"#trendChart"+i,$scope,"Time",$scope.sensorData.sensors[i].details.sensorName);
                                jQuery("#trendChart"+i).tooltip();
                        }
                                
                                        
                });
         
        }
         //Function to search device based on given searchString from devicelist
         $scope.searchForDevice = function(arr, searchString){
                 if(!searchString){
                         return arr;
                 }      
                 var result = [];
                 searchString = searchString.toLowerCase();
                 angular.forEach(arr, function(item){
                         if(item.name.toLowerCase().indexOf(searchString) != -1){
                                 result.push(item);
                         }      
                 });
                 return result;
        }
                //watches model "deviceSearchString" to get new values
         $scope.$watch('deviceSearchString', function (newVal, oldVal) {
                 $scope.filteredDevices = $scope.searchForDevice($scope.devices, newVal);
                 $scope.totalItems = $scope.filteredDevices.length;
                 $scope.noOfPages = Math.ceil($scope.totalItems / $scope.itemsPerPage);
                 $scope.currentPage = 1;
                }, true);
                
         //navigate to login page when you click on logout option in navigation
         $scope.logout = function(){
                 window.location = "index.html"
                 }                                      
  
        
}]);
<script src="http://ift.tt/1mslDRD"></script>

Here "getSensorDetails" is factory service which uses $resouce for REST service.

intelApp.factory('getSensorDetails',function($resource){
        return $resource('http://ift.tt/1rre87a',{},{
        //      return $resource('http://ift.tt/1W9lr09',{},{
        query: {
        method: 'GET',
        transformResponse: function(data, headers){
            response = {};
                        /*var temp=data.trim();
                        temp=temp.substring(1,data.length-2);
                        temp= temp.replace(/\\/g, "");*/
            response.data = JSON.parse(data);
            response.headers = headers();
            return response;
        }
        }});
});

I know how to write unit test case for straight functions but this controller shows more than that. It would be good if anyone can show how to write Unit test case for controller.

Thanks in Adavance Regards,

Aucun commentaire:

Enregistrer un commentaire