Skip to content

Instantly share code, notes, and snippets.

@stuartlangridge
Created June 11, 2014 23:06
Show Gist options
  • Save stuartlangridge/4d66733dde499a49203b to your computer and use it in GitHub Desktop.
Save stuartlangridge/4d66733dde499a49203b to your computer and use it in GitHub Desktop.
Multiple async tests against multiple objects with any JS test runner.
"use strict";
/*global process, console */
function Thingy() {}
Thingy.prototype.returns5 = function(cb) { process.nextTick(function() { cb(null, 5); }); };
Thingy.prototype.returns8 = function(cb) { process.nextTick(function() { cb(null, 8); }); };
var thingy1 = new Thingy(),
thingy2 = new Thingy(),
thingy3 = new Thingy(),
thingy4 = new Thingy();
/*
OK. We have four objects, thingy1-4. We want to test each of those objects
to confirm that (a) their returns5() method returns 5 (this is "returns"
by calling a callback; i.e., it's async) and that (b) their returns8() method
returns 8.
So, how?
Note that the test output ought to look like this:
Testing thingy1's returns5 function: pass
Testing thingy2's returns5 function: pass
Testing thingy3's returns5 function: pass
Testing thingy4's returns5 function: pass
Testing thingy1's returns8 function: pass
Testing thingy2's returns8 function: pass
Testing thingy3's returns8 function: pass
Testing thingy4's returns8 function: pass
i.e., each thing is a separate test.
But there should only be one function which tests whether
someobject.returns5() actually returns 5; not one function per item.
*/
@tgvashworth
Copy link

In reverse order:

Indeed, but any good assertion lib will say "got [x, y], expected [a, b]" and if those are related (and they must be, they're both being tested) then maybe it's not so bad. But neither of us would actually do that so it's moot.

To the testing thing, I suspect I'd write a set of helpers, so that my test code looked like:

var t = require('tap');

makeTestsFor('thingies', thingies, function (thingy, t) {
    t.test(thingy.name + ' returns 5', function (t) {
        thingy.returns5(function (err, res) {
            t.pass(res === 5);
            t.end();
        });
    });

    t.test(thingy.name + ' returns 8', function (t) {
        thingy.returns8(function (err, res) {
            t.pass(res === 8);
            t.end();
        });
    });

    t.end(); // not sure about the async properties of this
});

(edited to make betterer)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment