我将如何测试 Jasmine 中的 $scope.watch (AngularJS) 更改? [英] How would I test a $scope.watch (AngularJS) change in Jasmine?

查看:27
本文介绍了我将如何测试 Jasmine 中的 $scope.watch (AngularJS) 更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近才开始用 AngularJS 编写一些东西,但我不确定如何为这个特定的东西编写测试.我正在构建一个具有不同状态的帮助请求"模式.所以在我的控制器中,我使用了一个 $scope.request_mode 变量.激活帮助请求的不同链接将该变量设置为不同的值.

然后在我的指令中,我正在做一个 $scope.$watch('request_mode', function(){...}); 来选择性地激活或停用事物作为请求模式变化.代码都很好用,但我遇到的问题是测试.我似乎无法让 Jasmine 拿起 $scope.$watch 并在它发生变化时实际触发任何东西.

我敢肯定之前有人遇到过这种情况,因此非常感谢您提出任何建议.

解决方案

在您的单元测试中,您需要手动调用 $scope.$digest()>$scope.$apply() 触发 $scope.$watch().

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

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.

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.

I'm sure someone has run into this before, so any suggestions would be very much appreciated.

解决方案

In your unit tests you need to manually call $scope.$digest() or $scope.$apply() to trigger $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.

这篇关于我将如何测试 Jasmine 中的 $scope.watch (AngularJS) 更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆