单元测试角度指令,使用ngModel
问题描述:
我想单元测试使用ngModel并有困难的指令。看来,我的指令的链接功能永远不会被称为...单元测试角度指令,使用ngModel
这里是我的指令代码:
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;
}
}
}
}
}]);
这里是我的测试规范:
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)');
});
});
});
控制台日志输出“叫”从来没有发生,显然在我的测试规范elem从来没有更新。
我在做什么错?
答
原来,我没有在我的karma.config文件中包含指令:S。添加它解决了我所有的问题。
答
你可以尝试两件事。
首先,不是只使用字符串tpl,而是尝试angular.element()。
var tpl = angular.element('<core-unit ng-model="myUnit"></core-unit>');
其次,将tpl放在beforeEach块中。所以结果应该是这样的:
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();
}));
我想通了......我忘了将我的指令添加到我的karma.config文件中的文件数组。 :S – mcottingham 2014-09-02 20:04:12