All my unit tests have some common code I can run and abstract into a function. However I want to be able to re-use the Core
value in every test
function makeSuite(name, module, callback) {
suite(name, function () {
var Core = {};
setup(function () {
Core = Object.create(core).constructor();
Core.module("name", module);
});
teardown(function () {
Core.destroy();
});
callback(Core);
});
}
makeSuite("Server", server, function (Core) {
test("server creates a server", useTheCore);
test("server listens to a port", useTheCore);
test("server emits express app", useTheCore);
test("server destroys itself", useTheCore);
});
Each time I call useTheCore
I expect there to be a different value of the core. This is because the particular unit test library calls the setup
method before each test
. This clearly does not work because I'm passing {}
to the callback by value. And when I overwrite Core
it does not propagate.
One hack I can use is __proto__
to emulate pass by reference
function makeSuite(name, module, callback) {
suite(name, function () {
var ref = {};
setup(function () {
var Core = ref.__proto__ = Object.create(core).constructor();
Core.module("name", module);
});
teardown(function () {
ref.__proto__.destroy();
});
callback(ref);
});
}
- Is there a more elegant way to emulate pass by reference, preferably not using the deprecated non-standard
__proto__
- Is there a more elegant solution to the actual problem of code re-use I have.