Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 如何在单元测试中更改$watch值?_Angularjs_Unit Testing - Fatal编程技术网

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

Angularjs 如何在单元测试中更改$watch值?,angularjs,unit-testing,Angularjs,Unit Testing,我有一个如下的指令: angular.module('myApp', []) .directive('myDirective', function(){ return { link: function(scope, element, attr, controller) { scope.$watch('data', function(newValue, oldValue) { $timeout(function() {

我有一个如下的指令:

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);
        }
    };
});
我可以在单元测试中更改
数据
值并触发
$watch
,如下所示:

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

但是如何更改
myCtrl.search
值呢?我尝试了
scope.myCtrl.search=“new search”
,它返回错误
无法设置未定义的属性“search”

myCtrl
由于执行
ng controller=MyController as myCtrl
指令而附加到范围。因为这是一个单元测试,所以您也需要模拟myCtrl

在您执行以下操作的测试设置中

scope=$rootScope.$new()

还加

scope.myCtrl={}

设置虚拟变量(控制器)的步骤