2016-05-13 73 views
1

我有類似下面問題茉莉嘲諷服務

(function() { 

    var mockController = function ($scope, MockService) { 
     $scope.message = "This is a text message"; 
     $scope.getCities = function() { 
      return MockService.getCities(); 
     }; 

    }; 


    var mockService = function ($http) { 
     this.getCities = function() { 
      return $http.get("../rest/url", { 
       headers: { 
        'Accept': 'application/yang.data+json' 
       } 
      }); 
     }; 
    }; 

    angular.module("MockApp", []) 
     .service("MockService", mockService) 
     .controller("MockController", mockController); 

}()) 

我想寫一個UT嘲諷服務像下面

describe("MockController", function() { 

    var $scope; 

    beforeEach(function() { 
     module("MockApp"); 
     inject(function (_$controller_, _$rootScope_, MockService) { 
      $scope = _$rootScope_.$new(); 
      spyOn(MockService, "getCities").and.callFake(function() { 
       return [{ 
        city: "Bangalore" 
        , country: "India" 
       }]; 
      }); 
      controller = _$controller_("MockController", { 
       $scope: $scope 
      }); 

     }); 
    }); 

    describe("Test", function() { 

     it("Should be Bangalore", function() { 
      $scope.getCities() 
       .then(function (data) { 
        console.log("got it"); 
       }) 
     }); 
    }); 

}); 

它拋出一個錯誤說

控制器時

TypeError:$ scope.getCities(...)。然後不是函數

請幫幫我。

+0

這可能是一個愚蠢的問題,而是如何爲角的$ HTTP服務如何注入到你的服務?此外,您已爲您的MockService.getCitites()創建了一個不返回承諾對象的假。不要以爲你可以在僞返回類型上調用.then()函數。 – TSmith

+0

它存在於angular.js中 – robin

回答

0

我想:

$scope.getCities = function() { 
    return MockService.getCities(); 
}; 

應該是:

$scope.getCities = function() { 
    return MockService(getCities()); 
};