A. Duff
A. Duff

Reputation: 4309

Mocking ngModel in unit tests

I am trying to write unit tests for a directive that uses a link function and does not have any template associated with it. The directive requires ngModel like this:

angular.module('some-module', []).directive('someDirective', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attr, controller) {
      //Do something
    }
  };
});

When trying to unit test this, I'm just trying to compile a DIV to trigger the directive:

var $scope = $rootScope.$new();
var element = $compile('<div some-directive></div>')($scope);
$scope.$digest();

But this triggers an error that the ngModel controller cannot be found. After looking at the documentation for ngModel and ngModelController I've tried mocking ngModel using the $provide service like this:

beforeEach(module(function($provide) {
  var mockNgModel = {};
  $provide.value('ngModel', mockNgModel); //Doesn't work
  $provide.value('ngModelCtrl', mockNgModel); //Doesn't work
  $provide.value('ngModel.NgModelController', mockNgModel); //Doesn't work
  $provide.value('ngModel.ngModelController', mockNgModel); //Doesn't work
}));

I've also seen other solutions that talk about creating a property on the scope which contains whatever ngModel is bound to in the HTML where your directive is being used (e.g. solution1, solution2) but this has not solved the error in my case.

Upvotes: 3

Views: 1429

Answers (1)

HankScorpio
HankScorpio

Reputation: 3651

var $scope = $rootScope.$new();
$scope.foo = 'bar';
var element = $compile('<div some-directive ng-model="foo"></div>')($scope);
$scope.$digest();

Upvotes: 3

Related Questions