2016-02-17 34 views
1

我已经检查了其他类似于我的问题的问题。但是这个问题在各种情况下显然可能不同。 角茉莉花测试抱怨 类型错误:“未定义”不是(评估“fields.forEach”)的对象,在discoverDependentFields茉莉花测试抱怨'undefined'不是对象

这里是我的discoverDependentFields功能

discoverDependentFields($scope.response.Fields); 

function discoverDependentFields(fields) { 
    fields.forEach(function (field) { 
     field.DependencyFieldEvaluated = ''; 
     if (field.DependencyField) { 
      var foundFields = fields.filter(function (fieldToFind) { return fieldToFind.Name === field.DependencyField; }); 
      if (foundFields.length === 1) { 
       field.DependencyFieldEvaluated = foundFields[0]; 
      } 
     } 
    }); 
} 

,并在测试中,我有这个有点

 this.controller('MyController', { 
      '$scope': this.scope,        
      } 
     }); 

this.scope.response.Fields = [ 
       { 
        Name: "UserIdentity", 
        Value: { 
         "FirstName": "John" 
        }, 
        PropertyName: "User.Identity" 
       } 
      ]; 

我用field.DependencyFieldEvaluated的值的函数的指令,这样

function dependencyMet(field) { 
        var dependentField = field.DependencyFieldEvaluated; 

        var met = compareToDependencyValue(field, dependentField.Value); 
        return met; 
       } 

我不知道它为什么抱怨

+0

只是猜测这里,但考虑到它的样子'discoverDependentFields'被立即执行,应该不是你设置了'scope.response.Fields' *之前*运行'this.controller('MyController'...)'? – Phil

回答

2

如果

discoverDependentFields($scope.response.Fields); 

是在你的控制线,那么你需要设置$scope.response.Fields数据以前实例化控制器。换句话说,交换操作的顺序,在您的测试是

this.scope = {}; 
// or maybe this.scope = $rootScope.$new() 

this.scope.response = { 
    Fields: [{ 
     Name: "UserIdentity", 
     Value: { 
      FirstName: "John" 
     }, 
     PropertyName: "User.Identity" 
    }] 
}; 

this.controller('MyController', { 
    $scope: this.scope, 
}); 
+0

通过交换,我现在得到这个新的错误。 TypeError:'undefined'不是一个对象(评估'this.scope.response') – Maryam

+0

我假设你已经有了你的作用域上的'response'对象属性。检查我上面的编辑 – Phil

+0

谢谢菲尔,this.scope没有定义。我想知道为什么它在我将discoverDependentFields位添加到控制器之前工作。例如我有$ scope.completeApplicationFields = $ filter(“isNamedField”)(false,nonPrimaryFields,$ scope.response.Fields);和测试的方式是这样的 – Maryam