angularjs - 无法正确测试指令

时间:2016-04-22 10:01:45

标签: angularjs angularjs-directive karma-jasmine

我正在编写一些指令测试,但由于这个问题基本上是通过jquery插件创建的,因此我遇到了一些问题。

这是指令代码:

var setColor;

setColor = function(value) {
  var el, temperatureValue;
  el = $('.rs-range-color');
  temperatureValue = parseInt(value);
  el.attr('class', '');
  return el.addClass('rs-path rs-transition rs-range-color animate-color-change temp-' + temperatureValue);
};

$.fn.roundSlider.prototype.defaults.create = function() {
  var endLabel, numberTag1, numberTag2, o, startLabel;
  o = this.options;
  startLabel = this._valueToAngle(o.min);
  numberTag1 = this._addSeperator(startLabel, 'rs-tooltip-text custom-label num1 ');
  numberTag1.children().html(o.min).rsRotate(-startLabel);
  endLabel = this._valueToAngle(o.max);
  numberTag2 = this._addSeperator(endLabel, 'rs-tooltip-text custom-label num2 ');
  numberTag2.children().html(o.max).rsRotate(-endLabel);
  return setColor(o.value);
};

angular.module('Picker', []).directive('TemperaturePicker', function() {
  return {
    restrict: 'E',
    templateUrl: './directives/Picker/temperaturePicker.tpl.html',
    replace: true,
    link: function(scope, element, attrs) {
      element.roundSlider({
        min: attrs.min,
        max: attrs.max,
        radius: attrs.size,
        sliderType: 'min-range',
        startAngle: 315,
        circleShape: 'pie',
        width: 20,
        value: attrs.value,
        step: 0.5,
        editableTooltip: true,
        tooltipFormat: function(attrs) {
          return attrs.value.toFixed(1) + ' °C';
        }
      });
      return element.on('change drag', function(e) {
        if (e.value !== void 0) {
          return scope.$apply(function() {
            return setColor(e.value);
          });
        }
      });
    }
  };
});

这是我写的测试(如果失败,因为它说element.roundSlider不是函数):

describe('Directive: temperaturePicker', function() {
  var $compile, $rootScope;
  $rootScope = void 0;
  $compile = void 0;
  beforeEach(module('hgApp'));
  beforeEach(inject(function(_$rootScope_, _$compile_) {
    $compile = _$compile_;
    return $rootScope = _$rootScope_;
  }));
  return it('Should check that the directive is created', function() {
    var el;
    el = $compile("<temperature-picker></temperature-picker>")($rootScope);
    $rootScope.$digest();
    return expect(el).toBeDefined();
  });
});

它在$rootScope.$digest()后立即失败。

当测试运行时,肯定会调用Roundslider插件,正如您可以在karma调试控制台中看到的那样:

  

22 04 2016 10:58:27.679:DEBUG [middleware:source-files]:请求   /base/www-dev/js/roundSlider.min.js?44e96bb2359ffbafdb07fe8d60e7f95775e6d5ec

     

22 04 2016 10:58:27.679:DEBUG [中间件:源文件]:获取   C:/src/app-v5/www-dev/js/roundSlider.min.js 22 04 2016

     

10:58:27.679:DEBUG [web-server]:服务(缓存):   C:/src/app-v5/www-dev/js/roundSlider.min.js

任何类型的帮助都将非常感激。感谢

1 个答案:

答案 0 :(得分:0)

我相信您想使用jQuery从DOM中选择element,因此您的链接功能将如下所示:

link: function(scope, element, attrs) {
  $(element).roundSlider({ .......