我开始使用Angular和Jasmin测试并遵循角度教程,并为测试设置了此代码:
describe('PhoneListCtrl', function(){
beforeEach(module('phonecatApp'));
it('should create "phones" model with 3 phones', inject(function($controller) {
var scope = {},
ctrl = $controller('PhoneListCtrl', {$scope:scope});
expect(scope.phones.length).toBe(3); }));
});
我对这一行感到困惑:
var scope = {},
ctrl = $controller('PhoneListCtrl', {$scope:scope});
{$scope:scope}
做什么?我可以看到它将测试中的局部范围变量绑定到控制器的范围,但具体来说我无法弄清楚这个代码在做什么以及语法是否是Angular特定的。非常感谢您的帮助
答案 0 :(得分:2)
关于你的第一个问题:
它只允许一次声明多个变量:
var i = 0, j = 1;
与
相同var i = 0;
var j = 1;
关于你的第二个问题:
它允许传递通常应由angular注入的依赖项。简而言之,您将自己创建的作用域(以及一个空对象)注入控制器,而不是让angular创建作用域并将其注入控制器。这对于传递一个众所周知的范围,或传递模拟服务而不是服务的真实实现是有用的。
答案 1 :(得分:1)
JB Nizet的答案很明显,但只是为了真的清楚,因为你似乎是JS和Angular的新手,这里是注释代码和范围的不同名称,以说明测试所需的原因:
it('should create "phones" model with 3 phones', inject(function($controller) {
// A variable localized to this 'it' function that
// you can use to test results from the controller
var myTestScope = {};
// $controller(...) instantiates the controller and passes (injects) values.
// This is essentially what Angular does during the normal application execution.
var ctrl = $controller('PhoneListCtrl', { $scope: myTestScope });
// Now the controller been instantiated (executes its code). During this execution
// a property called 'phones' has been added to its $scope. This means myTestScope
// now contains this property and you can test its value.
expect(myTestScope.phones.length).toBe(3);
}));