faker-js / faker

Generate massive amounts of fake data in the browser and node.js
https://fakerjs.dev
Other
12.16k stars 885 forks source link

Ability to set the seed through environment variable #1651

Open sneko opened 1 year ago

sneko commented 1 year ago

Clear and concise description of the problem

Using another library that wraps faker.js, I wanted to set the seed (https://github.com/anatine/zod-plugins/issues/76).

After thinking more about it, and to avoid each library to implement this, I'm wondering if it would make sense for the underlying official library to detect a seed passed through an environment variable?

As you mentioned in the comment of https://github.com/faker-js/faker/blob/next/src/faker.ts#L288-L295 the need is to get same result across multiple iterations of tests for example. So it would do the trick.

The only issue I see is the chance of collision... but if it looks for process.env.FAKERJS_INITIAL_SEED I doubt someone on Earth has this for another purpose :D

Suggested solution

-

Alternative

Each wrapper needs to support the seed, and sometimes they don't manage a class (or a singleton), so you have to pass the seed everywhere you use their functions. In this last case, I need to use a helper to get the seed to easily pass it everywhere (but still, the wrapper needs to manage this).

Additional context

Thank you,

ST-DDT commented 1 year ago

Sounds like a valid proposal to me. One drawback/potential deviation from the expected behavior is running multiple test per file. Only the first test per file (or per faker import initialization) will use that seed, all subsequent tests will use a different value because the initial seed value is already consumed. Is that what you expect to happen?

sneko commented 1 year ago

Hmmm good catch @ST-DDT, I think it's problematic. It's very likely there are multiple tests in a same file, and adding a faker call in a test would make all subsequent tests changing... hard to track in case of "test snapshots" that are committed...

The only solution would be to have a beforeEach hook in tests, but it would imply having the authority to say to the faker.js wrapper to get the new side... so in all cases the wrapper needs to implement the seed method at the end.

Unfortunately I think the proposal has lose value due to this use case ^^... we can close if no good thoughts or alternatives.

Thanks for answering!