2016-02-27 47 views
0

我創建了一個角度自定義指令,其中包含一個名爲scriptingService的服務。目標是用spyOn嘲笑服務呼叫。這是測試的一部分:如何在茉莉花測試中模擬servicecall?

beforeEach(inject(function ($rootScope, $compile,_scriptingService_) { 
     scope = $rootScope.$new(); 
     scope.row = 1; 

     scriptingService = _scriptingService_; 
     Restangular = _Restangular_; 

     spyOn(Restangular, 'all').and.callThrough(); 

     spyOn(scriptingService, 'getScript').and.callThrough(); 

     element = angular.element('<ul id="rows" ui-list="row">'); 
     $compile(element)(scope); 
     scope.$digest(); 
    })); 

這是指令代碼:

.directive('uiList', [ 
    function(scriptingService) { 
     return { 
      scope: { 
       lengthModel: '=uiList' 
      }, 
      link: function(scope, elm, attrs) { 
       scope.$watch('lengthModel', function(newVal) { 
        scope.test=2; 
        console.log('kut'); 

        scriptingService.getScript(request).then(function(scripts){ 
         scope.scripts = scripts; 
        }); 

       }); 
      } 
     }; 
    } 
]); 

但是我得到一個錯誤:

RestangularProvider <- Restangular <- scriptingService 

我怎麼能嘲笑scriptingService並確保該方法被稱爲? Plunker編號:http://plnkr.co/edit/CDc7EV?p=preview

+0

你plunkr有幾個問題:老茉莉版本的新語法結合起來,and.callThrough()不工作1.3.1(更新茉莉或使用和CallThrough()),並且您的腳本服務在plunkr中不存在。 由於沒有向模塊註冊此類服務,因此預計在PLUNK上會出現「未知提供者」錯誤。 –

+0

我更新了plunkr並添加了scriptService。我嘲笑了Restangular,但仍然收到錯誤:錯誤:未知的提供者:RestangularProvider < - Restangular < - scriptingService –

+0

我無法在http://plnkr.co/edit/uhyzg6?p=preview –

回答

0

有幾個問題在這裏:

  1. 像評論上面說的,你需要使用茉莉花的新版本爲callThrough功能,而且還Restangular需要下劃線,所以需要在html文件中引用它。

  2. 另外,需要依賴注入來固定你的指令,因爲它不能夠注入scriptingService得當,它決不允許它來調用scriptingService.getScript因爲scriptingServiceundefined。問題是,

    [ function(scriptingService) {}] 
    

    將無法​​正常工作注入scriptingServiceuiList。它最後只是undefined

    它需要或者是

    ['scriptingService', function(scriptingService) {}] 
    

    OR

    function(scriptingService) {} 
    

    參考:https://docs.angularjs.org/guide/di#dependency-annotation

  3. request當它在這段代碼被使用從未定義,我不知道它應該是什麼。

    scriptingService.getScript(request).then(function(scripts) { 
    scope.scripts = scripts; 
    }); 
    
  4. 解決這些問題後,測試仍然失敗,說錯誤:意外的請求:GET /腳本。

    我能夠通過將$httpBackend(這是一個用於嘲笑http調用的服務)插入測試並期待請求來解決此問題。因此,我改變

    inject(function ($rootScope, $compile,_scriptingService_,_Restangular_) 
    

    TO

    inject(function ($rootScope, $compile,_scriptingService_,_Restangular_, $httpBackend) 
    

    ,並將此

    $httpBackend.expectGET("/scripting").respond([]); 
    
    spyOn的,那麼測試通過後

    。我不確定這個http調用應該返回什麼,但這只是你如何測試它的一個例子。

    參考:https://docs.angularjs.org/api/ngMock/service/ $ httpBackend