Javascript angularjs测试组件中的指令

Javascript angularjs测试组件中的指令,javascript,angularjs,unit-testing,jasmine,Javascript,Angularjs,Unit Testing,Jasmine,我使用的是AngularJS1.5。我有一个组件,它有一个电影列表(数组),并希望使用一个指令(电影项)呈现电影列表 我正在尝试对这个组件进行单元测试,确保它已经渲染了与电影列表数组长度匹配的电影 movieitem指令希望从用户那里收集输入,但我只是简化了它 我如何测试它 电影列表组件 (function() { "use strict"; var module = angular.module("psMovies"); function controller

我使用的是AngularJS1.5。我有一个组件,它有一个电影列表(数组),并希望使用一个指令(电影项)呈现电影列表

我正在尝试对这个组件进行单元测试,确保它已经渲染了与电影列表数组长度匹配的电影

movieitem指令希望从用户那里收集输入,但我只是简化了它

我如何测试它

电影列表组件

   (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]
    });

} ());
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();
    });

});
movie-list.component html

  <div ng-repeat="movie in model.movies">
        <movie-item item="movie"> </movie-item>
    </div>
 <div> {{model.id}}  - {{model.title}}</div> 
电影项目html

  <div ng-repeat="movie in model.movies">
        <movie-item item="movie"> </movie-item>
    </div>
 <div> {{model.id}}  - {{model.title}}</div> 

为了测试组件/指令模板,应使用
$compile
对其进行编译

测试这个的方法不止一种。如果嵌套的指令/组件太复杂,用虚拟指令/组件替换它们进行隔离测试是有意义的,即在
movieList
test
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
组件。@estus,我解决了这个问题。尝试在每个之前插入
(函数($componentController,\$rootScope)
,并将其分配给
$scope=\$rootScope.new()