@hazae41/phobos
Version:
Modern and minimalist testing library for the web
91 lines (87 loc) • 2.37 kB
JavaScript
'use strict';
var error = require('../error.cjs');
class Context {
message;
_befores = new Array();
_afters = new Array();
_catcher;
constructor(message) {
this.message = message;
this.test = this.test.bind(this);
this.before = this.before.bind(this);
this.after = this.after.bind(this);
this.catcher = this.catcher.bind(this);
this.wait = this.wait.bind(this);
}
/**
* Run something before each test block
* @param closure closure
*/
before(closure) {
this._befores.push(closure);
}
/**
* Run something after each test block
* @param closure closure
*/
after(closure) {
this._afters.push(closure);
}
/**
* Run something when an error is thrown
* @param closure
*/
catcher(closure) {
this._catcher = closure;
}
_tests = new Array();
/**
* Run a test block
* @param message message to show
* @param closure closure to run
* @returns result of closure
*/
async test(message, closure) {
const promise = this._test(message, closure);
this._tests.push(promise);
return promise.catch(() => { });
}
async _test(message, closure) {
const context = new Context(message);
for (const before of this._befores)
await before(context);
try {
await closure(context);
await context.wait();
}
catch (cause) {
const error$1 = new error.TestError(message, { cause });
if (!this._catcher)
throw error$1;
try {
await this._catcher?.(error$1, context);
}
catch (cause) {
throw new error.TestError(message, { cause });
}
}
finally {
for (const after of this._afters)
await after(context);
}
}
/**
* Wait for all tests to finish (called by default at the end of each test block)
* @why You want to forcefully wait in the midst of a test block
*/
async wait() {
try {
await Promise.all(this._tests);
}
finally {
this._tests = new Array();
}
}
}
exports.Context = Context;
//# sourceMappingURL=context.cjs.map