Chapter 8
Writing custom validation directive tests
The pattern for testing validation directives is to compile a form containing an input
that uses ng-model and our validation directive. For example:
<form name="testForm">
<input name="testInput"
ng-model="model.value"
validate-equals="model.compareTo">
</form>
This directive is an attribute on the input element. The value of the attribute is an
expression that must evaluate to the value on the model. The directive will compare
this value with the input's value.
We specify the model bound to this input using the ng-model directive. This
will create ngModelController, which will be exposed on the scope as $scope.
testForm.testInput and the model value itself will be exposed on the scope as
$scope.value.
We then make changes to the input value and the model value and check the
ngModelController for changes to $valid and $error.
In the test setup we keep a reference to the model and the ngModelController.
describe('validateEquals directive', function() {
var $scope, modelCtrl, modelValue;
beforeEach(inject(function($compile, $rootScope) {
...
modelValue = $scope.model = {};
modelCtrl = $scope.testForm.testInput;
...
}));
...
describe('model value changes', function() {
it('should be invalid if the model changes', function() {
modelValue.testValue = 'different';
$scope.$digest();
expect(modelCtrl.$valid).toBeFalsy();
expect(modelCtrl.$viewValue).toBe(undefined);
});
it('should be invalid if the reference model changes', function()
{
modelValue.compareTo = 'different';