1

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.
Raynos
  • 166,823
  • 56
  • 351
  • 396
  • I don't know if you'll consider this elegant, but it resolves the non-standard issue. Could you just place an ugly property on your `var Core = {};` object, like `Core.__core_internal_data__ = Object.create(core).constructor();`, and then have your API anticipate the existence of that property? Sort of like what NodeJS does with its event emitter system. –  Jan 10 '12 at 14:54
  • @amnotiam that means I have to change the callback to reference to be `function (_) { doSomething(_.Core); }` which is possible but ugly. I want to keep using that `Core` variable directly – Raynos Jan 10 '12 at 14:58
  • I don't suppose you'd consider it safe/reliable to `.apply()` the constructor to the existing prototype? So after the first time `setup` is called, you'd start doing `Object.create(core).constructor.apply(Object.getPrototypeOf(ref))` –  Jan 10 '12 at 16:00
  • @amnotiam turns out I don't actually need to do it like this. `Core.destroy()` cleanly resets the core to the initial state so I can keep applying `module` and `destroy` over and over again. – Raynos Jan 10 '12 at 16:15

0 Answers0