zulip/frontend_tests/zjsunit/namespace.js

91 lines
2.3 KiB
JavaScript
Raw Normal View History

const _ = require('underscore/underscore.js');
2016-07-30 17:00:12 +02:00
let dependencies = [];
const requires = [];
let old_builtins = {};
2016-07-30 17:00:12 +02:00
exports.set_global = function (name, val) {
global[name] = val;
dependencies.push(name);
return val;
};
exports.patch_builtin = function (name, val) {
old_builtins[name] = global[name];
global[name] = val;
return val;
};
exports.zrequire = function (name, fn) {
if (fn === undefined) {
fn = '../../static/js/' + name;
} else if (/^generated\/|^js\/|^shared\/|^third\//.test(fn)) {
// FIXME: Stealing part of the NPM namespace is confusing.
fn = '../../static/' + fn;
}
delete require.cache[require.resolve(fn)];
const obj = require(fn);
requires.push(fn);
set_global(name, obj);
return obj;
};
2016-07-30 17:00:12 +02:00
exports.restore = function () {
dependencies.forEach(function (name) {
delete global[name];
});
requires.forEach(function (fn) {
delete require.cache[require.resolve(fn)];
});
2016-07-30 17:00:12 +02:00
dependencies = [];
delete global.window.electron_bridge;
2016-07-30 17:00:12 +02:00
_.extend(global, old_builtins);
old_builtins = {};
};
2016-07-30 20:01:15 +02:00
exports.stub_out_jquery = function () {
set_global('$', function () {
return {
on: function () {},
trigger: function () {},
hide: function () {},
removeClass: function () {},
2016-07-30 20:01:15 +02:00
};
});
$.fn = {};
$.now = function () {};
};
exports.with_overrides = function (test_function) {
// This function calls test_function() and passes in
// a way to override the namespace temporarily.
const clobber_callbacks = [];
const override = function (name, f) {
const parts = name.split('.');
const module = parts[0];
const func_name = parts[1];
if (!_.has(global, module)) {
set_global(module, {});
}
global[module][func_name] = f;
clobber_callbacks.push(function () {
// If you get a failure from this, you probably just
// need to have your test do its own overrides and
// not cherry-pick off of the prior test's setup.
global[module][func_name] =
'ATTEMPTED TO REUSE OVERRIDDEN VALUE FROM PRIOR TEST';
});
};
test_function(override);
_.each(clobber_callbacks, function (f) {
f();
});
};