范围和编译在Angularjs指令测试中未定义

时间:2017-06-06 18:04:30

标签: javascript angularjs unit-testing karma-jasmine

我正在尝试为此指令创建一些测试。第一个是带有字母字符的keydown事件不应该更改元素的值。这是指令。

// PhoneInput directive for formatting phone input.
angular.module('app')
    .directive('phoneInput', function ($filter, $browser) {
        return {
            require: 'ngModel',
            link: function ($scope, $element, $attrs, ngModelCtrl) {
                var listener = function () {
                    var value = $element.val().replace(/[^0-9]/g, '');
                    $element.val($filter('tel')(value, false));
                };

                // This runs when we update the text field
                ngModelCtrl.$parsers.push(function (viewValue) {
                    return viewValue.replace(/[^0-9]/g, '').slice(0, 10);
                });

                // This runs when the model gets updated on the scope directly and keeps our view in sync
                ngModelCtrl.$render = function () {
                    $element.val($filter('tel')(ngModelCtrl.$viewValue, false));
                };

                $element.bind('change', listener);
                $element.bind('keydown', function (event) {
                    var key = event.keyCode;
                    // If the keys include the CTRL, SHIFT, ALT, or META keys, or the arrow keys, do nothing.
                    // This lets us support copy and paste too
                    if (key == 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) {
                        return;
                    }
                    $browser.defer(listener); // Have to do this or changes don't get picked up properly
                });

                $element.bind('paste cut', function () {
                    $browser.defer(listener);
                });
            }

        };
});

松散地跟随this guide,我为alpha的keydown创建了以下测试。

describe('phoneInput directive', function() {
    beforeEach(module('app'));

   // Define global references for injection
    var scope, compile, document, element, template;
    element = null;

    // making an input element that calls phoneInput
    template = 'input required name="tel" ng-model="tel" type="text" phone-input >';


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

    beforeEach(function(){
        element = compile(template)(scope);
        // spyOn keyDown
        spyon(scope, 'keydown');
    });

    it('should not accept alpha characters', function(){
        console.log(scope);
        console.log(compile);
       var givenEvent = {keyCode: 65};
       scope.$digest();

       element.triggerHandler('keydown', givenEvent);

       expect(element.val()).toEqual('');
    });
});

问题是测试打印出未定义范围和编译的错误。你看到有一个范围和范围的console.log;编译,经过测试,他们都吐出未定义的。

0 个答案:

没有答案