lundi 6 avril 2015

Test Angular's $valid and $pristine states with Jasmine

I have a Jasmine test that is not liking the use of $pristine and $valid within my controller and outputs the following error:



TypeError: 'scope[...].$pristine' is null or not an object


The test initiating this error is below:



it('should validate values correctly', function () {
var scp = ngElement.scope();

var tests = [
{
valid: true,
validationOptions: {
required: true
},
value: '1'
}
];

$.each(tests, function (testIndex, testItem) {
scp.name = 'test';
scp.value = testItem.value;
$.each(testItem.validationOptions, function (itemKey, itemValue) {
scp[itemKey] = itemValue;
});
scp.change();
expect(scp.valid).toBe(testItem.valid);
});
});


The function in the controller with the $pristine and $valid states is below:



// Field change behaviours
scope.change = function () {
validate();
...
};

// Field level validation function
function validate () {
// If the field does not have a value and is pristine, scope.valid is undefined.
// Otherwise the field is validated
if ((!scope.value || scope.value.length === 0) && scope[scope.name].$pristine) scope.valid = undefined;
else scope.valid = scope[scope.name].$valid;

...
}

Aucun commentaire:

Enregistrer un commentaire