如何测试$范围。《茉莉花》的变化?

时间:2022-12-02 20:22:13

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。美元的手表(request_mode,函数(){…});当请求模式改变时,有选择地激活或停用。代码都很好,但是我遇到的问题是测试。我似乎找不到茉莉花来买这幅画。$watch,当它发生变化时,它会自动射击。

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

我相信以前一定有人遇到过这种情况,所以任何建议都非常感谢。

1 个解决方案

#1


90  

In your unit tests you need to manually call $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。$在后台为您申请。

#1


90  

In your unit tests you need to manually call $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。$在后台为您申请。