【问题标题】:Catching errors on plugin initialization wth QUnit使用 QUnit 捕获插件初始化错误
【发布时间】:2013-05-14 18:21:41
【问题描述】:

我使用以下格式来创建插件。

$(function () {
  function PluginName() { 
    /* some more code here */ 
  }

  $.extend(PluginName.prototype, {
    _attachPlugin: function (target, options, value) {
      target = $(target);

      if (target.hasClass(this.shortenerClass)) {
        return;
      }

      var instance = {
        options: $.extend({}, this._defaults)
      };

      if (typeof instance.options.requiredOption === 'undefined') {
        throw 'You need required option!';
      }
    },
  });

  var getters = [/* some getters */];

  function isNotChained(method, otherArgs) {
    if (method === 'option' && (otherArgs.length === 0 ||
        (otherArgs.length === 1 && typeof otherArgs[0] === 'string'))) {
      return true;
    }
    return $.inArray(method, getters) > -1;
  }

  $.fn.pluginname = function (options) {
    var args = Array.prototype.slice.call(arguments, 1);

    if (isNotChained(options, args)) {
      return plugin['_' + options + 'Plugin'].apply(plugin, [this[0]].concat(args));
    }

    return this.each(function () {
      if (typeof options === 'string') {
        if (!plugin['_' + options + 'Plugin']) {
          throw 'Unknown method: ' + options;
        }
        plugin['_' + options + 'Plugin'].apply(plugin, [this].concat(args));
      } else {
        plugin._attachPlugin(this, options || {});
      }
    });
  };

  var plugin = $.pluginname = new PluginName();
})(jQuery);

当我传入我的选项对象时,我想确保某个选项存在。如果不是,则从 _attachPlugin 方法中抛出一个错误。错误被抛出,但是我无法让 QUnit 断言错误被抛出。目前我的测试是这样的:

test('Init error', function () {
  throws($('#selector').pluginname(), 'Throws error when missing required option.')
});

我认为我可以通过这样编写测试来测试错误:

test('Init error', function () {
  throws($.urlshortener._attachPlugin($('#selector')[0]), 'Throws an error');
});

无论我怎么写,两个测试都因 _attachPlugin 抛出的错误而死,这是 QUnit 没有捕捉到的。

【问题讨论】:

    标签: jquery jquery-plugins qunit


    【解决方案1】:

    您正在调用“抛出”断言,将函数结果作为块传递,而不是传递要调用的函数对象,这就是未捕获异常的原因。

    代替:

    test('Init error', function () {
      throws($('#selector').pluginname(), 'Throws error when missing required option.')
    });
    

    您应该将您的测试定义为:

    test('Init error', function () {
      throws(function() { $('#selector').pluginname() }, 'Throws error when missing required option.')
    });
    

    这样 QUnit 将调用函数对象并管理异常。

    我在这里放了一个工作示例:http://jsfiddle.net/hhk6u/9/

    关于 jQuery 插件的附加说明: 请注意,我已将插件代码的第一行从以下位置更改为:

    $(function () {
    

    到:

    ;(function ($) {
    

    这种方式可以避免插件自动启动,这通常是一个好习惯。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-27
      • 1970-01-01
      • 2020-05-02
      • 1970-01-01
      相关资源
      最近更新 更多