我如何访问这个'使用controllerAs时,单元测试中的控制器?

时间:2015-05-15 23:15:58

标签: angularjs unit-testing

我有一个简单的控制器:

myApp.controller('HelloController', function () {
  this.greeting = 'Hello!';
});

我想测试一下 - 但我无法像往常一样访问$scope

  beforeEach(inject(function (
    _$rootScope_,
    $controller
  ) {
    $rootScope = _$rootScope_;
    scope = $rootScope.$new();
    ctl = $controller('HelloController', {
      $scope: scope
    });
    scope.$apply();
  }));

  it('should call fetchArticle and set that to a property', function () {
    $rootScope.$apply();
    expect(scope.greeting).to.equal('hello');
  });

如何查看this的{​​{1}}?

1 个答案:

答案 0 :(得分:0)

如果你正在使用控制器,那么HelloController在这样的测试中将不再对你有用。相反,您需要查看从scope调用返回的值。您的测试将如此通过:

$controller

正如Dan Pantry在评论中所说,你不需要 it('should call fetchArticle and set that to a property', function () { $rootScope.$apply(); expect(ctl.greeting).to.equal('hello'); }); 来实例化HelloController。相反,您可以$controller