pic*_*ter 24 jasmine angularjs
我正在使用茉莉花进行angularJS测试.在我的视图中,我使用"Controller as"语法:
<div ng-controller="configCtrl as config">
<div> {{ config.status }} </div>
</div>
Run Code Online (Sandbox Code Playgroud)
如何在茉莉花中使用这些"范围"变量?"控制器"指的是什么?我的测试如下:
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");
});
});
Run Code Online (Sandbox Code Playgroud)
默认情况下scope.status,调用结束时会出现错误:
Expected undefined to be "any".
Run Code Online (Sandbox Code Playgroud)
更新:控制器(从TypeScript编译的javascript)如下所示:
var ConfigCtrl = (function () {
function ConfigCtrl($scope) {
this.status = "any";
}
ConfigCtrl.$inject = ['$scope'];
return ConfigCtrl;
})();
Run Code Online (Sandbox Code Playgroud)
Bey*_*ers 46
解决方案是在测试中实例化控制器时使用"控制器为"语法.特别:
$ 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");
});
});
Run Code Online (Sandbox Code Playgroud)
and*_*dam 15
当我们使用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");
});
});
Run Code Online (Sandbox Code Playgroud)