Angularjs 如何访问';这';使用Controllera时控制器在单元测试中的性能?

Angularjs 如何访问';这';使用Controllera时控制器在单元测试中的性能?,angularjs,unit-testing,Angularjs,Unit Testing,我有一个简单的控制器: myApp.controller('HelloController', function () { this.greeting = 'Hello!'; }); 我想测试它-但我无法像往常一样访问$scope: beforeEach(inject(function ( _$rootScope_, $controller ) { $rootScope = _$rootScope_; scope = $rootScope.$new(

我有一个简单的控制器:

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

如何检查
HelloController
this

如果您正在使用Controllera,
scope
将不再对您在此类测试中有用。相反,您需要查看调用
$controller
返回的值。您的测试将通过:

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

正如Dan Pantry在评论中所说,您不需要
$controller
来实例化HelloController。相反,您可以执行
新建HelloController()

,除非您在controller中实际使用
$scope
,否则
控制器语法的主要优点之一是您只需执行
新建HelloController()
,而不必通过注入器。不过,这只有在你使用像webpack这样的东西时才有效,但在我看来,这样更整洁。@DanPantry谢谢!我会在我的回答中加上这个。