test-fixture-factory
Version:
A minimal library for creating and managing test fixtures using Vitest, enabling structured, repeatable, and efficient testing processes.
81 lines (76 loc) • 2.07 kB
JavaScript
// src/define-fixture.ts
var defineFixture = (factoryFn, fixtureFn) => {
const wrappedFn = (deps, use) => {
return fixtureFn(deps, use);
};
wrappedFn.toString = () => {
return factoryFn.toString();
};
return wrappedFn;
};
// src/yn.ts
var yn = (input) => {
if (input === void 0 || input === null) {
return false;
}
const value = String(input).trim();
if (/^(?:y|yes|true|1|on)$/i.test(value)) {
return true;
}
if (/^(?:n|no|false|0|off)$/i.test(value)) {
return false;
}
return false;
};
// src/env-var.ts
var getSkipDestroyEnvVar = () => {
if (typeof process !== "undefined" && "env" in process) {
return yn(process.env.TFF_SKIP_DESTROY);
}
return false;
};
var SKIP_DESTROY = getSkipDestroyEnvVar();
// src/define-factory.ts
var defaultFactoryOptions = {
shouldDestroy: !SKIP_DESTROY
};
var defineFactory = (factoryFn) => {
const factory = factoryFn;
factory.useCreateFn = (options = defaultFactoryOptions) => defineFixture(factoryFn, async (deps, use) => {
const destroyList = [];
const createFn = async (attrs) => {
const { value, destroy } = await factoryFn(deps, attrs);
if (destroy) {
destroyList.push(destroy);
}
return value;
};
await use(createFn);
if (options.shouldDestroy) {
for (const destroy of destroyList) {
await destroy();
}
}
});
factory.useValueFn = (attrs, options = defaultFactoryOptions) => defineFixture(factoryFn, async (deps, use) => {
const { value, destroy } = await factoryFn(deps, attrs);
await use(value);
if (options.shouldDestroy) {
await destroy?.();
}
});
return factory;
};
// src/undefined-field-error.ts
var UndefinedFieldError = class extends Error {
constructor(options) {
const { factory, dependency, attribute } = options;
super(
`[${factory}] Undefined field: '${attribute}'. You must either define a '${dependency}' test fixture or supply the '${attribute}' attribute.`
);
}
};
export {
UndefinedFieldError,
defineFactory
};