Unit test angular that uses ngModel

I am trying to use the unit test directive, which uses ngModel and has difficulties. It seems that the link function of my directive is never called ...

Here is my directive code:

coreModule.directive('coreUnit', ['$timeout', function ($timeout) { return { restrict: 'E', require: '?ngModel', template: "{{output}}", link: function (scope, elem, attrs, ngModelCtrl) { ngModelCtrl.$render = function () { render(ngModelCtrl.$modelValue); }; console.log("called"); function render(unit) { if (unit) { var output = '(' + unit.numerator + (unit.denominator == '' ? '' : '/') + unit.denominator + (unit.rate == 'NONE' || unit.rate == '' ? '' : '/' + unit.rate) + ')'; scope.output = output == '()' ? '' : output; } } } } }]); 

Here is my test spec:

 describe('core', function () { describe('coreUnitDirective', function () { beforeEach(module('core')); var scope, elem; var tpl = '<core-unit ng-model="myUnit"></core-unit>'; beforeEach(inject(function ($rootScope, $compile) { scope = $rootScope.$new(); scope.myUnit = {}; elem = $compile(tpl)(scope); scope.$digest(); })); it('the unit should be empty', function () { expect(elem.html()).toBe(''); }); it('should show (boe)', function () { scope.myUnit = { numerator: 'boe', denominator: "", rate: "" }; scope.$digest(); expect(elem.html()).toContain('(boe)'); }); }); }); 

The console log output is called never, and obviously the item in my test spec is never updated.

What am I doing wrong?

+6
source share
2 answers

It turns out that I did not include the directive in my karma.config: S. file. By adding it to the resolved all my problems.

+3
source

You can try two things.

First, instead of using only the tpl string, try angular.element ().

 var tpl = angular.element('<core-unit ng-model="myUnit"></core-unit>'); 

Secondly, put tpl in the beforeEach block. The result should look like this:

 beforeEach(inject(function ($rootScope, $compile) { var tpl = angular.element('<core-unit ng-model="myUnit"></core-unit>'); scope = $rootScope.$new(); scope.myUnit = {}; elem = $compile(tpl)(scope); scope.$digest(); })); 
+2
source

Source: https://habr.com/ru/post/974560/


All Articles