在手表中测试角度的$viewContentLoaded
Testing angular's $viewContentLoaded in watch
有人可以指导我如何测试角度$viewContentLoaded
吗?我的控制器中对此有$watch
。
我的相关控制器代码:
$scope.$watch('$viewContentLoaded', function() {
$scope.variableOne= true;
});
这是我的相关茉莉花规格:
describe('Testing $viewContentLoaded', function() {
it('should be true', inject(function ($controller,$scope) {
$controller('MainCtrl');
// what to do to invoke $viewContentLoaded ???
$scope.$digest();
expect($scope.variableOne).toBe(true);
}));
});
普伦克尔代码
任何这方面的帮助将不胜感激!
$viewContentLoaded
事件仅在加载 DOM 时触发。因此,您需要以某种方式通过为其分配范围来将 DOM 放入图片MainCtrl
。
为此,我会说添加一个虚拟div
,并分配ng-controller="MainCtrl"
。然后使用MainCtrl
范围编译该div。因此,一旦你编译了那个div,在编译完那个div之后,它将广播$viewContentLoaded
将被听众收听(这就是为什么虚拟DOM在这里很重要)。
法典
var $scope;
describe('Testing $viewContentLoaded', function() {
it('should be true', inject(function($controller, $rootScope, $compile) {
$scope = $rootScope.$new();
$controller('MainCtrl', {
$scope: $scope
});
var div = '<div ng-controller="MainCtrl"></div>'
$compile(div)($scope);
$scope.$digest();
expect($scope.variableOne).toBe(true);
}));
});
在这里演示
注意:
$viewContentLoaded
事件应该通过将侦听器放在像$scope.$on
这样的$scope
上来侦听,而不是将监视放在上面 它。
你也可以这样做(假设你用$scope.$on而不是$watch来$viewContentLoaded):
$scope.$broadcast('$viewContentLoaded');
这可以防止加载任何 DOM
编辑:(回答巴舍里·莫马尼的问题)
因此,假设使用了$scope.$on('$viewContentLoaded'
而不是$scope.$watch('$viewContentLoaded'
,您可以在测试中调用$scope.$broadcast('$viewContentLoaded');
。这样,就不需要加载任何 DOM。
例如。
在控制器中,您可以拥有:
$scope.$on('$viewContentLoaded', function() {
$scope.variableOne= true;
});
在您的规范中,您可以像这样测试它:
describe('Testing $viewContentLoaded', function() {
it('should be true', inject(function ($controller, $rootScope) {
var $scope = $rootScope.$new();
$controller('MainCtrl', {
$scope: $scope
});
$scope.$broadcast('$viewContentLoaded');
expect($scope.variableOne).toBe(true);
}));
});
相关文章:
- 没有找到相关文章