私はコントローラをユニットテストする必要があります。まず、私は自分のサービスのためのモックを作成する必要があります。ここで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
をしかし、私はそれを呼び出すことはありませんでした。助けてください
更新された質問で別の方法をテストしていませんか? – tanmay
すみません。 spec.jsテストファイルを更新しました。 – sanjitguin
あなたの仕様で 'scope。$ apply()'を呼び出すのはなぜですか?それを削除するとどうなりますか? – tanmay