单元测试AngularJS Directive似乎没有执行Directive的Controller

时间:2016-01-12 23:24:45

标签: angularjs unit-testing jasmine

我已经按照许多指南对单元测试(简单)自定义指令进行了单元测试,但我很困惑的是指令似乎没有被执行(指令控制器永远不会触发)。我正在调用范围。$ digest来执行摘要循环。

Fiddle

//--- CODE --------------------------

angular.module("foo", [])
.directive('CreditCardDisplay', function () {
    return {
        restrict: 'E',
        scope: {
            card: '@'
        },
        controllerAs: 'vm',
        bindToController: true,
        controller: function () {
            var mask = null;
            console.log("in CreditCardDisplay, card: " + this.card);
            if (!_.isEmpty(this.card)) {
                var length = this.card.length;

                var card = this.card.slice(-4);

                switch (length) {
                    case 14:
                        mask = "****-******-";
                        break;
                    case 15:
                        mask = "****-******-*";
                        break;
                    case 16:
                        mask = "****-****-****-";
                        break;
                    default:
                        var l1 = Math.floor((length - 4) / 4);
                        var l2 = length - 4 - (l1 * 4);
                        mask = _.repeat("****-", l1) + _.repeat("*", l2) + "-";
                }
            }

            this.mask = mask ? mask + card : card;
        },
        template: '<span>{{vm.mask}}</span>'
    };
});

// --- SPECS -------------------------

describe("directive: gpCreditCardDisplay", function () {
    var element, scope, innerScope, elementCtrl;
    beforeEach(function () {
        module('foo');

        element = angular.element('<credit-card-display card="12345678901234"/>');

        inject(function($rootScope, $compile) {
            scope = $rootScope.$new();
            $compile(element)(scope);
            scope.$digest();
            innerScope = element.isolateScope;
            elementCtrl = innerScope.vm;
        });
    });

    // credit card

    it("when getting a 14 digit credit card number should return correctly formatted", function () {
        expect(element.text()).toContain("****-******-1234");
    });
});

1 个答案:

答案 0 :(得分:1)

查看更新的jsfiddle

几点。您的指令应命名为creditCardDisplay而不是CreditCardDisplay。有关命名的信息,请参阅angular guide

.directive('creditCardDisplay', function () {

如果要使用controllerAs语法,则应使用最新的角度。我认为它只在1.3版本中引入。你的jsfiddle使用的是角1.2。

虽然与此测试用例无关,但请注意element.isolateScope是一个函数,因此您应该调用element.isolateScope()