vitest-plugin-random-seed
Version:
Define and print an integer that can be used to seed libraries like [ChanceJS](https://github.com/chancejs/chancejs), [Falso](https://github.com/ngneat/falso), or [FakerJS](https://github.com/faker-js/faker).
37 lines (34 loc) • 818 B
JavaScript
;
let seed;
function RandomSeed(options) {
const shouldLog = seed == null;
seed ?? (seed = options?.seed ?? getEnvSeed() ?? getRandomSeed());
const definition = options?.define ?? "import.meta.test.SEED";
return {
name: "random-seed",
apply: (_, { mode }) => mode === "test",
config: () => {
if (shouldLog) {
console.log(`Test seed: \x1B[1m\x1B[36m${seed}\x1B[0m`);
}
return {
define: {
[definition]: JSON.stringify(seed)
}
};
}
};
}
function getRandomSeed() {
return Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
}
function getEnvSeed() {
const env = process.env.TEST_SEED?.trim();
if (!env)
return;
const num = Number(env);
if (isNaN(num))
return;
return num;
}
module.exports = RandomSeed;