2016-12-20 8 views
2

私はコントローラをユニットテストする必要があります。まず、私は自分のサービスのためのモックを作成する必要があります。ここでAngularJSユニットテスト用カルマジャスミンの模擬方法

は私のサービスである:ここでは

angular.module("demo-app") 
.factory("empService",function($http){ 

    var empService={}; 
    empService.getAllEmployees=function(){ 
     return $http.get("http://localhost:3000/api/employees"); 
    } 

    empService.postEmployee=function(emp){ 
     return $http.post("http://localhost:3000/api/employees",emp); 
    } 

    empService.getEmployee=function(id){ 
     return $http.get("http://localhost:3000/api/employees/"+id) 
    } 

    empService.putEmployee=function(emp){ 
     return $http.put("http://localhost:3000/api/employees/"+emp._id,emp) 
    } 

    empService.deleteEmployee=function(id){ 
     return $http.delete("http://localhost:3000/api/employees/"+id); 
    } 

    empService.findEmployee=function(emp){ 
     return $http.post("http://localhost:3000/api/employees/search",emp); 
    } 

    return empService; 
}) 

は、私がテストに行きます私のコントローラでfindData()メソッド、次のとおりです。

$scope.findData=function(){ 
    $scope.loadingEmployee=true; 
    var emp={}; 
    listProp=Object.getOwnPropertyNames($scope.searchEmployee); 
    for(index in listProp){ 
     if($scope.searchEmployee[listProp[index]]!=""){ 
      emp[listProp[index]]=$scope.searchEmployee[listProp[index]]; 
     } 
    } 
    console.log(emp); 
    empService.findEmployee(emp).then(function(data){ 
     $scope.allEmployees=data.data; 
     console.log(data.data); 
     $scope.loadingEmployee=false; 
    }); 
} 

どのように私は私のempService.findEmployee(EMPを模擬することができます)メソッドを使用して、findData()メソッドをテストできます。

私のspec.jsテストファイルは、私のサービスメソッドを嘲笑しています。ここでは、次のとおりです。

beforeEach(function(){ 
    var emp={"name":"sanjit"}; 
    fakeService={ 
     getAllEmployees:function(emp){ 
      def=q.defer(); 
      def.resolve({data:[{"name":"sanjit"},{'name':'ssss'}]}); 
      return def.promise; 
     }, 
     findEmployee:function(emp){ 
      var def=q.defer(); 
      def.resolve({data:[{"name":"sanjit"}]}); 
      console.log("working"); 
      return def.promise; 
     } 
    }; 
    spyOn(fakeService,'findEmployee').and.callThrough(); 
    fakeService.findEmployee(emp); 
}); 
beforeEach(angular.mock.inject(function($rootScope,$controller,$injector,$q){ 
    httpBackend=$injector.get('$httpBackend'); 
    scope=$rootScope.$new(); 
    q=$q; 
    ctrl=$controller('adminEmployeeCtrl',{$scope:scope,empService:fakeService}); 
})); 

it('findData test',function(){ 
    scope.$apply(); 
    scope.findData(); 
    expect(scope.loadingEmployee).toEqual(false); 
}) 

しかし、私は別のエラーました:

Error: Unexpected request: GET dashboard/views/dashboard-new.html 
No more request expected 

をしかし、私はそれを呼び出すことはありませんでした。助けてください

+0

更新された質問で別の方法をテストしていませんか? – tanmay

+0

すみません。 spec.jsテストファイルを更新しました。 – sanjitguin

+0

あなたの仕様で 'scope。$ apply()'を呼び出すのはなぜですか?それを削除するとどうなりますか? – tanmay

答えて

1

GET dashboard/views/dashboard-new.htmlを手動で呼び出すことはできませんでしたが、$scope.$apply()が何らかの形でそれを引き起こしている可能性があります。

あなたがそれを処理するために、このような何かを行うことができます:あなたが必要としないさangularjsでコントローラをテストする場合(_$httpBackend_を使用して、それを注入し、beforeEach$httpBackendに割り当てた後)で最も重要なルールの

$httpBackend.when('GET', 'dashboard/views/dashboard-new.html').respond(200); 
scope.$digest(); 
$httpBackend.flush(); 
+0

それは動作します。ありがとう@ tanmay – sanjitguin

0

ワンreall httpリクエストを作成するには、コントローラで使用されているそのサービスの機能をモックしてください。だからあなたはそれらをスパイする必要があり、適切な値を返すために偽関数を呼び出す必要があります。それらのうちの1つをスパイしよう

/** 
* @description Tests for adminEmployeeCtrl controller 
*/ 
(function() { 

    "use strict"; 

    describe('Controller: adminEmployeeCtrl ', function() { 

     /* jshint -W109 */ 
     var $q, $scope, $controller; 
     var empService; 
     var errorResponse = 'Not found'; 


     var employeesResponse = [ 
      {id:1,name:'mohammed' }, 
      {id:2,name:'ramadan' } 
     ]; 

     beforeEach(module(
      'loadRequiredModules' 
     )); 

     beforeEach(inject(function (_$q_, 
            _$controller_, 
            _$rootScope_, 
            _empService_) { 
      $q = _$q_; 
      $controller = _$controller_; 
      $scope = _$rootScope_.$new(); 
      empService = _empService_; 
     })); 

     function successSpies(){ 

      spyOn(empService, 'findEmployee').and.callFake(function() { 
       var deferred = $q.defer(); 
       deferred.resolve(employeesResponse); 
       return deferred.promise; 
       // shortcut can be one line 
       // return $q.resolve(employeesResponse); 
      }); 
     } 

     function rejectedSpies(){ 
      spyOn(empService, 'findEmployee').and.callFake(function() { 
       var deferred = $q.defer(); 
       deferred.reject(errorResponse); 
       return deferred.promise; 
       // shortcut can be one line 
       // return $q.reject(errorResponse); 
      }); 
     } 

     function initController(){ 

      $controller('adminEmployeeCtrl', { 
       $scope: $scope, 
       empService: empService 
      }); 
     } 


     describe('Success controller initialization', function(){ 

      beforeEach(function(){ 

       successSpies(); 
       initController(); 
      }); 

      it('should findData by calling findEmployee',function(){ 
       $scope.findData(); 
       // calling $apply to resolve deferred promises we made in the spies 
       $scope.$apply(); 
       expect($scope.loadingEmployee).toEqual(false); 
       expect($scope.allEmployees).toEqual(employeesResponse); 
      }); 
     }); 

     describe('handle controller initialization errors', function(){ 

      beforeEach(function(){ 

       rejectedSpies(); 
       initController(); 
      }); 

      it('should handle error when calling findEmployee', function(){ 
       $scope.findData(); 
       $scope.$apply(); 
       // your error expectations 
      }); 
     }); 
    }); 
}()); 
+0

あなたのコーディング標準はすばらしく見えます。何らかの理由でトリガされた予期せぬリクエストに対してはエラーが発生します。 エラー:予期しない要求:GET http:// localhost:3000/api/employees これ以上要求はありません – sanjitguin

関連する問題