简体   繁体   中英

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:

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

But how can I change the myCtrl.search value? I tried with scope.myCtrl.search = "new search" and it return error Cannot set property 'search' of undefined

myCtrl gets attached to the scope due to the ng-controller=MyController as myCtrl directive execution. Since this is a unit test you need to mock the myCtrl too.

In the test setup where you do

scope = $rootScope.$new()

also add

scope.myCtrl={};

to setup a dummy variable (controller)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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