Skip to content

Instantly share code, notes, and snippets.

@mk-pmb
Created November 10, 2016 13:05
Show Gist options
  • Save mk-pmb/c8f4918d101d78ffe6dc48f330bbbf6c to your computer and use it in GitHub Desktop.
Save mk-pmb/c8f4918d101d78ffe6dc48f330bbbf6c to your computer and use it in GitHub Desktop.
An easy way to manage unit test amenities. Originally posted in https://github.com/stevemao/better-than-before/issues/6
const amenityDefs = {
dbConn: {
provide() { db.connect(login); },
dispose() { db.disconnect(); },
},
dummyTable: {
provide() { db.createTable('dummy', dummySchema); },
dispose() { db.dropTable('dummy'); },
},
dummyData: {
provide() { db.tbl('dummy').restore(dummyData); },
dispose() { db.tbl('dummy').restore([]); },
},
};
const testDefs = {};
(function defTests(arr) {
var prevTestFunc;
arr.forEach(function (spec) {
if ((typeof spec) !== 'function') {
return Object.assign(prevTestFunc, spec);
}
prevTestFunc = spec;
testDefs[spec.name] = spec;
test(spec.name, spec);
});
}([
function connectToDatabase() {
assert.ok(!!db.socket);
},
{ need: [ 'dbConn' ] },
function measureTableLength() {
var cnt = db.tbl('dummy').countItems();
assert.strictEqual((typeof cnt), 'number');
assert.ok(cnt >= 0);
},
{ need: [ 'dbConn', 'dummyTable' ] },
function lookupFirstItem() {
var item = db.tbl('dummy').getByProp('id', 1);
assert.strictEqual(item.type, 'comment');
},
{ need: [ 'dbConn', 'dummyTable', 'dummyData' ] },
]));
function adjustAmenities(need) {
Object.keys(currentAmenities).forEach((amn) => {
if (need.indexOf(amn) >= 0) { return; }
amenityDefs[amn].dispose();
delete currentAmenities[amn];
});
need.forEach((amn) => {
if (objHas(currentAmenities, amn)) { return; }
currentAmenities[amn] = amenityDefs[amn].provide();
});
}
test.beforeEach(function (testId) {
var testFunc = testDefs[testId],
requiredAmenities = testFunc.need;
adjustAmenities(requiredAmenities);
});
test.after(() => { adjustAmenities([]); });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment