简体   繁体   English

如何在单元测试中更改$ watch的值?

[英]How to change $watch value in unit test?

I have a directive that look like this: 我有一个看起来像这样的指令:

angular.module('myApp', [])
.directive('myDirective', function(){
    return {
        link: function(scope, element, attr, controller) {
            scope.$watch('data', function(newValue, oldValue) {
                $timeout(function() {
                    if (newValue !== oldValue) {
                        console.log('data Changed!');
                    }
                });
            },true);

            scope.$watch('myCtrl.search', function(newValue, oldValue) {
                $timeout(function() {
                    if (newValue !== oldValue) {
                        console.log('myCtrl.search Changed!');
                    }
                });
            },true);
        }
    };
});

I am able to change the data value and triggle the $watch in unit test with this: 我可以更改data值并使用以下命令在单元测试中触发$watch

scope.data = "new data";
scope.$digest();

But how can I change the myCtrl.search value? 但是,如何更改myCtrl.search值? I tried with scope.myCtrl.search = "new search" and it return error Cannot set property 'search' of undefined 我尝试使用scope.myCtrl.search = "new search" ,它返回错误Cannot set property 'search' of undefined

myCtrl gets attached to the scope due to the ng-controller=MyController as myCtrl directive execution. myCtrl被附连到范围由于ng-controller=MyController as myCtrl指令执行。 Since this is a unit test you need to mock the myCtrl too. 由于这是一个单元测试,因此您也需要模拟myCtrl。

In the test setup where you do 在测试设置中,您要做的是

scope = $rootScope.$new()

also add 还添加

scope.myCtrl={};

to setup a dummy variable (controller) 设置虚拟变量(控制器)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM