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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:28:27  来源:igfitidea点击:

How would I test a $scope.watch (AngularJS) change in Jasmine?

jqueryangularjsjasmineangularjs-directivejasmine-jquery

提问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.$watchand 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-clickdo $rootScope.$applyfor you behind the scenes.

通常在您的代码中您不必这样做,因为指令就像在幕后为您ng-click做的那样$rootScope.$apply