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

问题描述

我使用angularJS测试茉莉。在我的看法,我使用的控制器语法:

 < D​​IV NG控制器=configCtrl为配置>
    < D​​IV> {{config.status}}< / DIV>
< / DIV>

我如何使用这些茉莉花范围变量?什么是控制器是指什么?
我的测试看起来如下:

 描述('ConfigCtrl',函数(){
    VAR范围;    beforeEach(angular.mock.module('busybee'));
    beforeEach(angular.mock.inject(函数($ rootScope){
        范围= $ rootScope $新的()。        $控制器('configCtrl',{$范围:适用范围});
    }));    它('应该有文字=任何',函数(){
        期待(scope.status).toBe(任何);
    });
});

调用 scope.status 结束,可以肯定,出现错误:

 预计不确定的是任何。

更新:控制器(从打字稿编译的JavaScript)看起来是这样的:

  VAR ConfigCtrl =(函数(){
    功能ConfigCtrl($范围){
        this.status =任何;
    }
    。ConfigCtrl $注射='$范围'];
    返回ConfigCtrl;
})();


解决方案

解决方法就是在您的测试实例控制器时使用的控制器语法。具体做法是:

$控制器( configCtrl作为配置',{$范围:适用范围});

期望( scope.config.status )TOBE(任何);

下面现在应该通过:

 描述('ConfigCtrl',函数(){
    VAR范围;    beforeEach(angular.mock.module('busybee'));
    beforeEach(angular.mock.inject(函数($控制器,$ rootScope){
        范围= $ rootScope $新的()。        $控制器('configCtrl为配置',{$范围:适用范围});
    }));    它('应该有文字=任何',函数(){
        期待(scope.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");
    });
});

这篇关于如何使用针对&quot范围变量;控制器&QUOT;语法茉莉花?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 19:23