【问题标题】:Unit test angular directive that uses ngModel使用 ngModel 的单元测试角度指令
【发布时间】:2014-08-29 17:32:27
【问题描述】:

我正在尝试对使用 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 文件中的 files 数组中。 :S

标签: angularjs unit-testing angularjs-directive karma-jasmine


【解决方案1】:

原来我没有在我的 karma.config 文件中包含该指令:S。添加它解决了我的所有问题。

【讨论】:

    【解决方案2】:

    你可以尝试两件事。

    首先,不要只使用字符串 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();
    }));
    

    【讨论】:

      猜你喜欢
      • 2015-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 2020-11-11
      • 1970-01-01
      • 2013-07-13
      相关资源
      最近更新 更多