pQuestions123
pQuestions123

Reputation: 4611

writing a unit test for an angular directive that requires ng-model

I am new to unit testing and trying to figure out how to set it all up. I have the following directive:

(function () {
    'use strict';

    angular
        .module('hntb-utils')
        .directive('notZero', notZero);

    //notZero.$inject = [];

    function notZero() {
        return {
            require: 'ngModel',
            link: link,
            restrict: 'A',
            scope: '='
        };

        function link(scope, element, attributes, ngModelCtrl) {
            ngModelCtrl.$validators.notZero = function (value) {
                return value != 0;
            }
        }
    }

})();

This directive (if added as an attribute not-zero to an element that also uses ng-model) ensures that the model value is not zero by adding a validator to the ngModelController.

I am trying to figure out how to test this directive. I figure I should probably have something like:

it("should ensure model is not zero", function () {
...
});

I am just really stuck on the implementation. I know I should use angular-mocks but how? What do I mock up?

Thanks in advance.

Upvotes: 1

Views: 2376

Answers (1)

ryeballar
ryeballar

Reputation: 30088

You can make use of the $compile service to compile an input element with an ngModel directive and notZero directive. Get the ngModelController of that element by using the .controller() method. Afterwards, manipulate the scope model of that element to apply multiple test cases.

Here is a demo.

describe('notZero', function() {

  var scope, 
    ngModel;

  beforeEach(module('hntb-utils'));

  beforeEach(inject(function($compile, $rootScope) {

    scope = $rootScope.$new();

    var input = $compile('<input type="number" ng-model="model" not-zero />')(scope);

    ngModel = input.controller('ngModel');

  }));

  it("should validate a non-zero number as a valid number", function () {

    scope.model = -1;
    scope.$apply();
    expect(ngModel.$error.notZero).toBeFalsy();

    scope.model = 1;
    scope.$apply();
    expect(ngModel.$error.notZero).toBeFalsy();

  });

  it("should validate a zero number as an invalid number", function() {

    scope.model = 0;
    scope.$apply();
    expect(ngModel.$error.notZero).toBeTruthy();

  });

});

Upvotes: 3

Related Questions