UNPKG

test-fns

Version:

write usecase driven tests systematically for simpler, safer, and more readable code

45 lines 1.82 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.usePrep = void 0; const helpful_errors_1 = require("helpful-errors"); /** * .what = declare a resource to be prepared before tests * .why = simplifies devexp by letting you write `const thing = usePrep(...)` * .mode = * - 'beforeAll': prepare once for all tests * - 'beforeEach': prepare fresh for each test run */ const usePrep = (setup, options = { mode: 'beforeAll' }) => { // metaphor: "drawer" = proxy target, "toolbox" = real resolved resource const drawer = {}; // exposed object users access let toolbox; // holds the resolved result of setup() // declare proxy handler up front so we can mutate it const proxyHandler = { get(_, prop) { if (toolbox === undefined) throw new helpful_errors_1.UnexpectedCodePathError('usePrep: tried to access value before setup completed'); return toolbox[prop]; }, ownKeys() { return Reflect.ownKeys(drawer); }, getOwnPropertyDescriptor(_, prop) { return Object.getOwnPropertyDescriptor(drawer, prop); }, apply() { throw new Error('usePrep: value is not callable'); }, }; const register = options.mode === 'beforeEach' ? beforeEach : beforeAll; register(async () => { toolbox = await setup(); // assign properties from toolbox to drawer so Object.keys(), for..in, etc work Object.assign(drawer, toolbox); // remove get trap once setup is complete — access becomes direct delete proxyHandler.get; }); // return a proxy that looks and feels like toolbox return new Proxy(drawer, proxyHandler); }; exports.usePrep = usePrep; //# sourceMappingURL=usePrep.js.map