jquery - Catching errors on plugin initialization wth QUnit -
i'm using following format creating plugins.
$(function () { function pluginname() { /* 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 = [/* 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);
when pass in options object, want make sure option there. if not, throw error _attachplugin method. error being thrown unable qunit assert error thrown. test looks this:
test('init error', function () { throws($('#selector').pluginname(), 'throws error when missing required option.') });
i thought test error writing test so:
test('init error', function () { throws($.urlshortener._attachplugin($('#selector')[0]), 'throws error'); });
either way write it, both tests dying on error being thrown _attachplugin qunit not catching.
you calling "throws" assertion passing function result block instead of passing function object called, that's why exception not being caught.
instead of:
test('init error', function () { throws($('#selector').pluginname(), 'throws error when missing required option.') });
you should define test as:
test('init error', function () { throws(function() { $('#selector').pluginname() }, 'throws error when missing required option.') });
this way qunit call function object , manage excpetions.
i put working example here: http://jsfiddle.net/hhk6u/9/
additional notes jquery plugins: note in example i've changed first line of plugin code from:
$(function () {
to:
;(function ($) {
this way avoids plugin start automatically, , practice.
Comments
Post a Comment