【问题标题】:How to use scope variables with the "Controller as" syntax in Jasmine?如何在 Jasmine 中使用具有“Controller as”语法的范围变量?
【发布时间】:2013-08-27 19:08:16
【问题描述】:

我正在使用 jasmine 进行 angularJS 测试。在我看来,我使用的是“Controller as”语法:

<div ng-controller="configCtrl as config">
    <div> {{ config.status }} </div>
</div>

如何在 jasmine 中使用这些“范围”变量? “控制器为”指的是什么? 我的测试如下所示:

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

    beforeEach(angular.mock.module('busybee'));
    beforeEach(angular.mock.inject(function($rootScope){
        scope = $rootScope.$new();

        $controller('configCtrl', {$scope: scope});
    }));

    it('should have text = "any"', function(){
        expect(scope.status).toBe("any");
    });
}); 

调用scope.status 肯定会以错误结束:

Expected undefined to be "any".

更新:控制器(从 TypeScript 编译的 javascript)如下所示:

var ConfigCtrl = (function () {
    function ConfigCtrl($scope) {
        this.status = "any";
    }
    ConfigCtrl.$inject = ['$scope'];
    return ConfigCtrl;
})();

【问题讨论】:

  • 至少,你应该这样做expect(scope.config.status).toBe("any");
  • 请提供configCtrl的代码,as语法几乎就像$scope.config = this;this.status = "any";一样。
  • 如果我在控制器中手动定义$scope.config = this;,它就可以工作。但我认为这不是应有的方式,不是吗?

标签: angularjs jasmine


【解决方案1】:

解决方案是在您的测试中实例化您的控制器时使用“controller as”语法。具体来说:

$controller('configCtrl as config', {$scope: scope});

expect(scope.config.status).toBe("any");

以下内容现在应该通过了:

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

    beforeEach(angular.mock.module('busybee'));
    beforeEach(angular.mock.inject(function($controller,$rootScope){
        scope = $rootScope.$new();

        $controller('configCtrl as config', {$scope: scope});
    }));

    it('should have text = "any"', function(){
        expect(scope.config.status).toBe("any");
    });
}); 

【讨论】:

  • 不幸的是,这对我不起作用。我在$controller('configCtrl as config', {$scope: scope}); 行收到错误Error: Argument 'configCtrl as config' is not a function, got undefined in path/to/angular.js (line 1039)
  • 应该可以,请参阅 AngularJS 自己的“控制器作为”功能测试代码github.com/angular/angular.js/blob/v1.2.0-rc.3/test/ng/…
  • @3x14159265 还有两件事要检查/尝试:(1) 注入 $controller,例如beforeEach(inject(function ($controller, $rootScope) {。 (2) 确保加载了定义 configCtrl 的模块。我在 AngularJS 1.2.0 RC3 中使用这种语法没有任何错误。
  • 有效!谢谢。这应该被标记为答案。
【解决方案2】:

当我们使用controller as 语法时,应该不需要将 $rootScope 注入到我们的测试中。以下应该可以正常工作。

describe('ConfigCtrl', function(){
    beforeEach(module('busybee'));

    var ctrl;

    beforeEach(inject(function($controller){
        ctrl = $controller('ConfigCtrl');
    }));

    it('should have text = "any"', function(){
         expect(ctrl.status).toBe("any");
    });
});

【讨论】:

  • 有时您仍然需要访问控制器内部的 $scope,即使您使用的是controller as
猜你喜欢
  • 2016-01-24
  • 2014-12-26
  • 2017-12-25
  • 2015-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-14
相关资源
最近更新 更多