2017-07-02 84 views
0

我正在使用angular js 1.5。我有一個組件有一個電影列表(數組),並期望使用指令(電影項目)呈現電影列表。angularjs測試組件中的指令

我想單元測試這個組件,並確保它已經呈現與電影列表數組長度匹配的電影。

電影項目指令希望收集來自用戶的輸入,但我只是簡化它。

我該如何測試?

電影列表組件

(function() { 
    "use strict"; 

    var module = angular.module("psMovies"); 

    function controller() { 
     var model = this; 
     model.movies = []; 

     model.$onInit = function() { 
      model.movies = [{"id": 1,"title": "Star Wars"},{"id": 2,"title": "Star Trek"}];   
     }; 
    } 

    module.component("movieList", { 
     templateUrl: "movie-list.component.html", 
     controllerAs: "model", 
     controller: [ controller] 
    }); 

}()); 

電影list.component HTML

<div ng-repeat="movie in model.movies"> 
     <movie-item item="movie"> </movie-item> 
    </div> 

電影項組件

angular.module('psMovies') 
    .directive('movieItem', function() { 
     "use strict"; 
     return { 
      templateUrl: 'movie-item.component.html', 
      restrict: 'EA', 
      scope: { 
       item: '=', 
      }, 
      link: function(scope) { 

      } 
     }; 
    }); 

電影項目HTML

<div> {{model.id}} - {{model.title}}</div> 

我的單元測試

describe("The movieList component", function() { 

    beforeEach(module("psMovies")); 

    var moviesList; 
    beforeEach(inject(function ($componentController) { 
     moviesList = $componentController("movieList",{ 
      $scope: {} 
     }); 
    })); 

    it("can be created", function() { 
     expect(moviesList).toBeDefined(); 
     expect(moviesList.$onInit).toBeDefined(); 
    }); 

}); 
+0

的問題是不夠清晰。哪一個是「指令」,哪一個是「組件」。您發佈的代碼中只有'movieItem' *組件*。 – estus

+0

@estus,我解決了這個問題。 – dream123

+0

嘗試注入'beforeEach(注入(函數($ componentController,_ $ rootScope_)''並將其分配給'$ scope = _ $ rootScope.new()_; –

回答

0

爲了測試組件/指令模板,應該與$compile編譯。

有多種測試方法。如果嵌套的指令/組件過於複雜,則將其替換爲虛擬指令/組件用於隔離測試是有意義的,即在movieList測試movieItem可以被嘲笑,只是爲了測試它在movieList模板中正確綁定,如:

describe('movieList tests',() => { 
    beforeEach(module('psMovies', ($provide) => { 
    $provide.directive('movieItem',() => ({ 
     scope: { item: '=' } 
    })); 
    }); 
    ... 
    it('should compile movie items', inject(($rootScope) => { 
    let scope = $rootScope.$new(); 
    const movieList = $compile('<movie-list>')(scope); 
    $rootScope.$digest(); 
    const mockedMovieItems = movieList.find('movie-item'); 
    expect(mockedMovieItems.length).toBe(2); 
    const mockedMovieItem = mockedMovieItems[0]; 
    expect(mockedMovieItem.isolateScope().item).toEqual({"id": 1,"title": "Star Wars"}); 
    ... 
    })); 
}); 

真正movieItem然後可以單獨進行測試:

describe('movieItem tests',() => { 
    beforeEach(module('psMovies')); 
    ... 
    it('should compile movie items', inject(($rootScope) => { 
    let scope = $rootScope.$new(); 
    scope.movie = {"id": 1,"title": "Star Wars"}; 
    const movieItem = $compile('<movie-item item="movie">')(scope); 
    $rootScope.$digest(); 
    expect(movieItem.isolateScope().item).toEqual({"id": 1,"title": "Star Wars"}); 
    ... 
    })); 
});