2015-04-26 130 views
3

我想爲使用eonasdan-bootstrap-datetimepicker(https://github.com/Eonasdan/bootstrap-datetimepicker)的指令編寫單元測試。對於該指令的代碼看起來是這樣的:AngularJS單元測試DateTimePicker

'use strict'; 

angular.module('directives') 
.directive('datepicker', ['$moment', function ($moment) { 
    return { 
     restrict: 'A', 
     require: 'ngModel', 
     link: function (scope, element, attributes, ctrl) { 
      angular.element(document).ready(function(){ 
       var jElem = $(element); 
       jElem.datetimepicker({ 
        icons: { 
         time: "fa fa-clock-o", 
         date: "fa fa-calendar", 
         up: "fa fa-arrow-up", 
         down: "fa fa-arrow-down", 
         next: "fa fa-arrow-right", 
         previous: "fa fa-arrow-left" 
        }, 
        format: 'D MMMM' 
       }); 
       var picker = jElem.data("DateTimePicker"); 

       ctrl.$parsers.push(function (value) { 
        var date = $moment(value); 
        if (date.isValid()) { 
         return date.format('D/M'); 
        } 
        return ''; 
       }); 

       $(element).on('dp.change', function (event) { 
        scope.$apply(function() { 
         var date = picker.date(); 
         if (date && date.valueOf) { 
          ctrl.$setViewValue(date.valueOf()); 
         } 
        }); 
        element[0].blur(); 
       }); 
      }); 
     } 
    }; 
}]); 

我試圖讓事件「dp.change」覆蓋,但我無法弄清楚如何觸發一個jQuery事件。我試着做這樣的事情:

'use strict'; 

describe('Specs for datepicker', function() 
{ 
    var scope; 
    var $compile; 
    var form; 

    beforeEach(module('directives')); 
    beforeEach(inject(function($rootScope, _$compile_) { 
     $compile = _$compile_; 
     scope = $rootScope.$new(); 
     var html = "<form name='test_form'"+ 
          " novalidate>"+ 
          "<fieldset>"+ 
           "<input type='text' "+ 
             "ng-model='dt' "+ 
             "datepicker "+ 
             "class='form-control date' "+ 
             "name='date' "+ 
             "value=''/>"+ 
          "</fieldset>"+ 
        "</form>" 
     form = $compile(angular.element(html))(scope); 
     scope.$digest(); 
    })) 

    it('should react to dp.change', function() 
    { 
     scope.test_form.date.$setViewValue('1 Jan'); 
     scope.$digest(); 
     var element = $(form).find('input'); 
     var dp = $(element.find('datepicker')); 
     dp.triggerHandler(new $.Event('dp.change')); 
     scope.$digest(); 
     expect(scope.dt).toEqual('1/1'); 
    }); 
}); 

我試了一堆其他的東西,但沒有讓我覆蓋處理程序。任何建議如何解決這個問題?

回答

0

在您的測試,簡單地通過

form = $compile(html)(scope); 

問題取代

form = $compile(angular.element(html))(scope); 

由任一

form = $compile(angular.element('<div>' + html + '</div>'))(scope); 

或是angular.element條遠頂端父元素傳遞給$compile之前。

0

你應該嘗試

scope.test_form.date.$setViewValue('1 Jan'); 
scope.$digest(); 
var element = $(form).find('input'); 
element.triggerHandler(new $.Event('dp.change')); 
expect(scope.dt).toEqual('1/1');