本文介绍了如何将范围变量与“Controller as"一起使用?茉莉花的语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<div ng-controller="configCtrl as config">

{{ config.status }} </div></div>

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

describe('ConfigCtrl', function(){变量范围;beforeEach(angular.mock.module('busybee'));beforeEach(angular.mock.inject(function($rootScope){范围 = $rootScope.$new();$controller('configCtrl', {$scope: scope});}));it('应该有 text = "any"', function(){期望(范围.状态).toBe(任何");});});

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

预期未定义为任何".

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

var ConfigCtrl = (function () {函数 ConfigCtrl($scope) {this.status = "任何";}ConfigCtrl.$inject = ['$scope'];返回配置控件;})();
解决方案

解决方案是在测试中实例化控制器时使用controller as"语法.具体来说:

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

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

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

describe('ConfigCtrl', function(){变量范围;beforeEach(angular.mock.module('busybee'));beforeEach(angular.mock.inject(function($controller,$rootScope){范围 = $rootScope.$new();$controller('configCtrl as config', {$scope: scope});}));it('应该有 text = "any"', function(){期望(范围.config.status).toBe(任何");});});

I'm using jasmine for angularJS testing. In my views, I'm using the "Controller as" syntax:

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

How can I use these "scope" variables in jasmine? What does the "Controller as" refer to?My test looks like following:

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

Calling scope.status ends, for sure, with the error:

Expected undefined to be "any".

UPDATE: Controller (compiled javascript from TypeScript) looks like this:

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

The solution is to use the "controller as" syntax when instantiating your controller in your test. Specifically:

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

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

The following should now pass:

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 as"一起使用?茉莉花的语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 19:23