2017-07-02 87 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"}); 
    ... 
    })); 
});