Skip to content

Instantly share code, notes, and snippets.

@dugancathal
Created June 28, 2018 04:24
Show Gist options
  • Save dugancathal/2c090513a031a1abae60ec67fa41d076 to your computer and use it in GitHub Desktop.
Save dugancathal/2c090513a031a1abae60ec67fa41d076 to your computer and use it in GitHub Desktop.
Just for funzies - you can include all of TJSpec in your codes to get a functioning test framework. DON'T FORGET TO CALL `run()`
const results = TJSpec.describe('A Suite', (it) => {
it('passes with no exceptions', () => {
});
it('throws an exception when an exception fails', (assert) => {
try {
assert.true(false, 'should fail');
} catch (e) {
return assert.true(true);
}
assert.true(false, 'should never reach this');
});
it('asserts when two things are equal', (assert) => {
try {
return assert.equals(2 + 2, 4);
} catch (e) {
return assert.true(false);
}
assert.true(false, 'should never reach this');
});
it('continues when something fails', (assert) => {
const results = TJSpec.describe('inner test', (it) => {
it('throws, but continues', () => {
throw new Error('OH NOES!');
});
it('runs', () => {
assert.true(false);
});
}).run();
assert.equals(results.length, 2);
assert.equals(results[0].error, 'OH NOES!');
assert.equals(results[1].error, 'Expected: false to be true');
});
}).run();
console.log(results);
const TJSpec = {
_suites: [],
describe: function (desc, suite) {
const _currentSuite = {
desc,
specs: [],
assert: this.assert,
run: function () {
return this.specs.map(spec => spec.spec());
}
};
suite(this.it.bind(_currentSuite));
this._suites.push(_currentSuite);
return _currentSuite;
},
it: function (desc, spec) {
this.specs.push({
desc,
spec: () => {
try {
spec(this.assert);
} catch (e) {
return { desc, error: e.message, passed: false };
}
return { desc, passed: true };
}
});
},
assert: {
true: (actual) => { if (actual !== true) throw new Error(`Expected: ${actual} to be true`) },
equals: (actual, expected) => { if (actual != expected) throw new Error(`Expected: ${actual} to == ${expected}`) },
},
run: function () {
return this._suites.map(suite => suite.run());
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment