带Karma的AngularJS测试控制器

Sha*_*oon 6 unit-testing angularjs karma-runner

我的控制器是:

angular.module('mean').controller('ItemsController', ['$scope', function ($scope) {
  $scope.contentTemplate = '/views/items/index.html';
  $scope.subMenu = [
    {name: 'Create Item', location: '/items/create'}
  ];
}]);
Run Code Online (Sandbox Code Playgroud)

我的测试非常简单:

  describe('ItemsController', function () {
    var scope;

    beforeEach(module('mean'));

    beforeEach(inject(function($controller, $rootScope) {
      scope = $rootScope.new();
      $controller('ItemsController', {
        $scope: scope
      });

    }));


    it('should have sub menu items loaded properly', function () {
      expect(scope.subMenu.length).toBe(1);
    });

  });
Run Code Online (Sandbox Code Playgroud)

我想要的是测试有一个subMenu项目.相反,我得到的错误是:

PhantomJS 1.9.7(Mac OS X)ItemsController应该正确加载子菜单项FAILED TypeError:'undefined'不是函数(评估'$ rootScope.new()')

是不是注入了$ rootScope?那为什么它未定义?

Rob*_*Rob 19

你想要以美元符号开头的方法:

scope = $rootScope.$new();
//                 ^
Run Code Online (Sandbox Code Playgroud)

那应该解决它.