【问题标题】:Unit tests for Angular js directive for ui-mask用于 ui-mask 的 Angular js 指令的单元测试
【发布时间】:2017-06-23 06:18:21
【问题描述】:

我有一个名为 maskUI 的指令

.directive('uiMask', function () {
    return {
        template: '<input ui-mask="{{maskPattern}}"/>',
        replace: true,
        scope: true,
        require: 'ngModel',
        link: function (scope, element, attrs, ngModelCtrl) {
            var maskPattern = attrs.uiMaskPattern;
            scope.maskPattern = maskPattern;

            function eventHandler(e) {
                scope.$apply(function () {
                    var isFocused = (document.activeElement.id === element.context.id);
                    if (e.type === 'mouseover') {
                        scope.maskPattern = maskPattern;
                    }
                    else if (e.type === 'mouseleave' || e.type === 'blur') {
                        if (!isFocused && ngModelCtrl.$modelValue === '') {
                            scope.maskPattern = '';
                        }
                    }
                });
            }

            if (!ngModelCtrl.$viewValue) {
                scope.maskPattern = '';
            }

            element.on('mouseover mouseleave blur', eventHandler);
        }
    };
});

我如何开始为此指令编写单元测试

我开始喜欢

'use strict';

describe('DIRECTIVES: MASK', function () {

    beforeEach(module('app'));

    var $compile, $rootScope, $scope;

    beforeEach(inject(function (_$compile_, _$rootScope_) {
        $compile = _$compile_;
        $rootScope = _$rootScope_;
        $scope = $rootScope.$new();
    }));

    it('should mask the element', function () {
    });

});

我想在这个测试中也测试这些鼠标事件。我如何涵盖这些..如果有人可以帮助解决这个问题。谢谢你

【问题讨论】:

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


    【解决方案1】:

    实际上你不需要这个指令的模板......

    无论如何在单元测试中触发事件你都可以这样做:

    var template = '<input ui-mask="xxx">',
        element = $compile(template)($scope);
    //Trigger mouseover
    element.triggerHandler('mouseover');
    
    //function you wanna test after mouseover be triggered
    

    【讨论】:

    • 谢谢,让我试试这个
    猜你喜欢
    • 2015-05-03
    • 1970-01-01
    • 2013-10-18
    • 1970-01-01
    • 2015-01-18
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    • 2012-11-10
    相关资源
    最近更新 更多