我想实现一个依赖于范围变量的测试。我想启用ng-switch-when来解析表达式。这就是我想要(UPDATE使用$ rootScope)做:测试AngularJS范围变量
it('should switch on array changes', inject(function($rootScope, $compile) {
element = $compile(
'<div ng-switch="select">' +
'<div ng-switch-when="test[0]">test[0]:{{test[0]}}</div>' +
'</div>')($rootScope);
expect(element.html()).toEqual('<!-- ngSwitchWhen: test[0] -->');
$rootScope.test = ["leog"];
$rootScope.select = "leog";
$rootScope.$apply();
expect(element.text()).toEqual('test[0]:leog');
}));
我的问题是我对这个工作的实施并没有得到范围变量“测试”,以评估并按我的预期工作。这里是执行:
var ngSwitchWhenDirective = ngDirective({
transclude: 'element',
priority: 800,
require: '^ngSwitch',
compile: function(element, attrs) {
return function(scope, element, attr, ctrl, $transclude) {
var expr = scope.$eval(attrs.ngSwitchWhen),
ngSwitchWhen = expr !== undefined ? expr : attrs.ngSwitchWhen;
ctrl.cases['!' + ngSwitchWhen] = (ctrl.cases['!' + ngSwitchWhen] || []);
ctrl.cases['!' + ngSwitchWhen].push({ transclude: $transclude, element: element });
};
}
});
有没有人知道我在做什么错?任何帮助将不胜感激。
提前致谢!
UPDATE
我想弄清楚,这是一个如何NG-开关它正在从角团队测试的例子。只是为了表明我以类似的方式进行测试,但没有达到预期的结果。
此外,我忘记将我的代码转换为$ rootScope,直到现在您所看到的是我尝试创建新范围以避免依赖$ rootScope进行更改的尝试之一。
it('should switch on value change', inject(function($rootScope, $compile) {
element = $compile(
'<div ng-switch="select">' +
'<div ng-switch-when="1">first:{{name}}</div>' +
'<div ng-switch-when="2">second:{{name}}</div>' +
'<div ng-switch-when="true">true:{{name}}</div>' +
'</div>')($rootScope);
expect(element.html()).toEqual(
'<!-- ngSwitchWhen: 1 --><!-- ngSwitchWhen: 2 --><!-- ngSwitchWhen: true -->');
$rootScope.select = 1;
$rootScope.$apply();
expect(element.text()).toEqual('first:');
$rootScope.name="shyam";
$rootScope.$apply();
expect(element.text()).toEqual('first:shyam');
$rootScope.select = 2;
$rootScope.$apply();
expect(element.text()).toEqual('second:shyam');
$rootScope.name = 'misko';
$rootScope.$apply();
expect(element.text()).toEqual('second:misko');
$rootScope.select = true;
$rootScope.$apply();
expect(element.text()).toEqual('true:misko');
}));
它在测试之外工作吗?测试运行时element.text()会返回什么? – UnicodeSnowman
是的,它可以在真实的用例上工作。当测试运行** element.text()时**为''(空字符串)。调试它我发现编译内部函数的范围变量没有“test”属性,就像我对真实用例所做的那样。也许这与范围可视性有关。 – LeoG
这可能会揭示我的无知,但你能确认你的测试目标吗?看起来你已经发布了ngSwitch的AngularJS源码:当你试图测试它吗? –