UNPKG

@hazae41/phobos

Version:

Modern and minimalist testing library for the web

89 lines (86 loc) 2.33 kB
import { TestError } from '../error.mjs'; 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 = new TestError(message, { cause }); if (!this._catcher) throw error; try { await this._catcher?.(error, context); } catch (cause) { throw new 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(); } } } export { Context }; //# sourceMappingURL=context.mjs.map