[AngularJS + Unit Testing] Testing Directive's controller with bindToController, controllerAs and isolate scope

<div>
    <h2>{{vm.userInfo.number}} - {{vm.userInfo.name}}</h2>
</div>
'use strict';

class CardTitleInformCtrl {

    constructor() {

    }
}

function CardTitleInformDirective() {
    return {
        restrict: 'EA',
        scope: {},
        bindToController: {
            userInfo: '='
        },
        replace: true,
        template: require('./card-title-inform.html'),
        controller: CardTitleInformCtrl,
        controllerAs: 'vm'
    };
}

export default (ngModule) => {
    ngModule.directive('comCardTitleInform', CardTitleInformDirective);
};

Test:

export default (ngModule) => {
    describe('card title inform test', () => {

        var $scope, $compile, html, directiveName, directiveElm, controller;
        html = '<com-card-title-inform userInfo="userInfo"></com-card-title-inform>',
        directiveName = 'comCardTitleInform';

        beforeEach(window.module(ngModule.name));
        beforeEach(inject(function(_$compile_, _$rootScope_){
            $scope = _$rootScope_.$new();
            $compile = _$compile_;

            directiveElm = $compile(angular.element(html))($scope);
            controller = directiveElm.controller(directiveName);
            $scope.$digest();
        }));

        it('should has an h2 element with text 888-888-888 - Wan', function () {

            // Assign the data to the controller -- Because we use bindToController
            controller.userInfo = {
                name: "Wan",
                number: "888-888-888"
            };
            // ControllerAs as 'vm', assign controller to the $scope.vm
            $scope.vm = controller;
            // Make it work
            $scope.$digest();

            expect(directiveElm.find('h2').text()).toEqual(controller.userInfo.number + ' - ' +controller.userInfo.name);
        });
    });
};
原文地址:https://www.cnblogs.com/Answer1215/p/4893556.html