I experimented with QUnit checks and was looking for a good method to override functions using mocks to allow more atom tests. There are good solutions for specific cases, such as overriding $ .ajax ( Simple jQuery (1.5+) AJAX Mocking ), but I looked for a more general approach and came up with the following:
// Constructor for overrides. function overrides(overrides) { this.overrides = overrides; } // Implementation for overrides. overrides.prototype = { set: function () { var functions = {}; $.each(this.overrides, function (key, value) { eval("functions['" + key + "'] = " + key + ";"); eval(key + " = value;"); }); this.functions = functions; }, reset: function () { var functions = this.functions; $.each(this.overrides, function (key, _) { eval(key + " = functions['" + key + "'];"); }); } }
What can then be used as:
module("Comments", { setup: function () { this.overrides = new overrides({ "$.ajax": function (url, options) { alert("ajax: " + url + ', ' + options); } }); this.overrides.set(); }, teardown: function () { this.overrides.reset(); } });
Now everything seems to be working fine, and although this might not be the worst use of eval (), I was wondering if this could really be written without using eval ()? I read a few other eval () questions here and tried various options such as accessing overrides using the window [], but this does not work for the $ .ajax case, for example (window ['$']. Ajax works, but not the window ['$. ajax']).
Perhaps I also think it's hard, and eval () can be used safely here, or is there a better approach at all for overriding functions?
source share