jQuery 我将如何测试 Jasmine 中的 $scope.watch (AngularJS) 更改?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17112446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How would I test a $scope.watch (AngularJS) change in Jasmine?
提问by Mike Pelletier
I've just recently started writing something with AngularJS and I'm not sure how to go about writing a test for this particular thing. I'm building a "Help Request" mode that has different states. So in my controller, I use a $scope.request_mode variable. The different links to activate help requests set that variable to something differently.
我最近才开始用 AngularJS 编写一些东西,但我不确定如何为这个特定的东西编写测试。我正在构建一个具有不同状态的“帮助请求”模式。所以在我的控制器中,我使用了一个 $scope.request_mode 变量。激活帮助请求的不同链接将该变量设置为不同的值。
Then inside my directive, I'm doing a $scope.$watch('request_mode', function(){...});
to selectively activate or deactivate things as the request mode changes. The code all works great, but the problem I'm having is with testing. I cannot seem to get Jasmine to pick up the $scope.$watch
and actually fire anything when it changes.
然后在我的指令中,我正在做一个$scope.$watch('request_mode', function(){...});
有选择地激活或停用请求模式改变的事情。代码都很好用,但我遇到的问题是测试。我似乎无法让 Jasmine 拿起$scope.$watch
并在它发生变化时实际触发任何东西。
I'm sure someone has run into this before, so any suggestions would be very much appreciated.
我敢肯定之前有人遇到过这个问题,所以任何建议都将不胜感激。
回答by g00fy
In your unit tests you need to manuallycall $scope.$digest()
or $scope.$apply()
to trigger $scope.$watch()
.
在您的单元测试中,您需要手动调用$scope.$digest()
或$scope.$apply()
触发$scope.$watch()
.
Normally in your code you wouldn't have to do this, since directives like ng-click
do $rootScope.$apply
for you behind the scenes.
通常在您的代码中您不必这样做,因为指令就像在幕后为您ng-click
做的那样$rootScope.$apply
。