Question

I am new to the world of JavaScript and Angular, and I am using Karma and Jasmine to test code. I am having a difficult time figuring out how to test angular directive.

The directive validates the date of birth to validate users age is above 55. Here's a simplified version of the code:

Here is the (relevant) html:

<div ng-controller="datepickerCtrl">
<input type="text" dobpicker-popup="{{format}}" name="dob" ng-model="dob" 
is-open="opened" dobpicker-options="dateOptions" min-date="minDate" 
required="true" dobcheck/>
</div>

Javascript code (The date format used is dd/MM/yyyy)

Module.directive('dobcheck', function($log) {
    return {
        require: 'ngModel',
        scope : true,
        link : function(scope, element, attrs, ctrl)
        {
            ctrl.$parsers.unshift(function(value) {

                if(evaluateAge(value) > 55)
                {
                    ctrl.$setValidity('dobcheck', true);
                    return value;
                }
                else
                {
                    ctrl.$setValidity('dobcheck', false);
                    return value;
                }
            });
        }
    }
});

This block is used to generate the current age

function evaluateAge(dob)
{
    var today = new Date();
    var bDate = new Date(dob);
    var age = today.getFullYear() - bDate.getFullYear();
    var months = today.getMonth() - bDate.getMonth();

    if (months < 0 || (months === 0 && today.getDate() < bDate.getDate()))
    {
        age--;
    }

    return age;
}

Unit test used to test scenario

'use strict';

describe('Age Validation directive', function() {
  var $scope, form;

  beforeEach(module('Regux'));

  beforeEach(inject(function($compile, $rootScope) {
  $scope = $rootScope;

    var element = angular.element(
      '<form name="form">' +
      '<div>' +
        '<input ng-model="model.dob" name="dob" 
       required="true" dobcheck="model.dob"/>' +
      '</div>'+
      '</form>');

    $scope.model = { dob: null }  
    $compile(element)($scope);
    form = $scope.form;
  }));

  describe('validate Date of Birth ', function() {

  it('Age over 55', function() {
    form.dob.$setViewValue('04/05/1955');
    $scope.$digest();
    expect($scope.model.dob).toEqual('04/05/1955');
    expect($scope.model.dob).toBe('04/05/1955');
    expect(form.dob.$valid).toBe(true);
    });
  });
});

Error displayed

Age over 55 FAILED -TypeError: Cannot read property '$valid' of undefined at  null.<anonymous>`

Any suggestion on how how I can fix this error and any best practices on to test a AngularJS directive like this?

Thanks

Était-ce utile?

La solution

The last assert statement should be

expect(form.dob.$valid).toBe(true);

since your input's name is dob not dobcheck.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top