Maryam
Maryam

Reputation: 1496

Jasmine test complaining about 'undefined' is not an object

I have checked other questions similar to my problem. but this problem can apparently be different in every case. Angular Jasmine Test complains TypeError: 'undefined' is not an object (evaluating 'fields.forEach')at discoverDependentFields

Here is my discoverDependentFields function

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];
            }
        }
    });
}

and in the test I have this bit

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

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

I use the value of field.DependencyFieldEvaluated in a function in a directive like this

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

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

I have no idea why it is complaining

Upvotes: 1

Views: 1816

Answers (1)

Phil
Phil

Reputation: 164733

If

discoverDependentFields($scope.response.Fields);

is a line in your controller, then you need to setup the $scope.response.Fields data before instantiating the controller. In other words, swap the order of operations in your test to be

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,
});

Upvotes: 2

Related Questions