2016-02-28 59 views
1

我試圖寫一個單元測試我自定義指令:我該如何做成功的單元測試?

.directive('uiList', [ 
    function(scriptingService) { 
     return { 
     scope: { 
      lengthModel: '=uiList' 
     }, 
     link: function(scope, elm, attrs) { 
      scope.$watch('lengthModel', function() { 
      scriptingService.getScript(request).then(function(scripts) { 
       //something 
      }); 
      }); 
     } 
     }; 
    } 

裏面我所說的服務:

.service('scriptingService', function() { 
    var scriptingService = { 
     getScript: function() { 
     return 'blaat'; 
     } 
    }; 

    return scriptingService; 
    }) 

我想測試getScript加入方法是否被調用,所以我寫了這個測試;

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

    scriptingService = _scriptingService_; 
    spyOn(scriptingService, 'getScript'); 
    element = angular.element('<ul id="rows" ui-list="row">'); 
    $compile(element)(scope); 
    scope.$digest(); 
    elementScope = element.scope(); 
    })); 

    it('should call service', function() { 


    scope.$apply(function() { 
     scope.row = 2; 
    }); 

    expect(scriptingService.getScript).toHaveBeenCalled(); 

    }); 

目前,我得到一個錯誤: 類型錯誤:無法讀取的未定義的屬性「getScript加入」。 爲什麼我得到這個錯誤,我該如何解決它?我以爲我已經嘲笑這項服務了?

plunkr:http://plnkr.co/edit/IQOCut?p=preview

+1

你定義用[]語法您的指令,但你忘了給DI名稱: 'scriptingService' + monior設置更改:http://plnkr.co/edit/HxTuU5?p=preview – ronapelbaum

回答

0

乾淨的版本 - http://plnkr.co/edit/8SVlzG?p=preview

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

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


it('should call service', function() { 

    scope.$apply(function() { 
     scope.row = 2; 
    }); 

    expect(elementScope.test).toEqual(1); 

    }); 
相關問題