gpt4 book ai didi

angularjs - 如何在 Jasmine 中使用具有 "Controller as"语法的范围变量?

转载 作者:行者123 更新时间:2023-12-03 10:48:04 25 4
gpt4 key购买 nike

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

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

如何在 Jasmine 中使用这些“范围”变量? “ Controller 为”指的是什么?
我的测试如下所示:
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".

更新 : Controller (从 TypeScript 编译的 javascript)看起来像这样:
var ConfigCtrl = (function () {
function ConfigCtrl($scope) {
this.status = "any";
}
ConfigCtrl.$inject = ['$scope'];
return ConfigCtrl;
})();

最佳答案

解决方案是在测试中实例化 Controller 时使用“ Controller 为”语法。具体来说:

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

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

关于angularjs - 如何在 Jasmine 中使用具有 "Controller as"语法的范围变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18473574/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com