efate icon indicating copy to clipboard operation
efate copied to clipboard

Let initialize the internal instance counter

Open Charly-xepelin opened this issue 4 months ago • 0 comments

The Fixture class internally initializes its counter at 1.

export default class Fixture<T> {
  private omittedFields: Set<keyof T> = new Set();
  private builders: BuilderGeneratorFunction<T>[] = [];
  private instanceCount: number;

  constructor(builders: BuilderGeneratorFunction<T>[], extendFixture: Array<Fixture<T>>) {
    this.instanceCount = 1; // <-----------
    this.builders = builders;
    

    if (extendFixture.length > 0) {
      this.builders.push(...extendFixture.map(fixture => fixture.builders).flat());
    }
  }

I used it to generate data in a integration test, and I wanted to keep the old records generated, but every run of the test started generating values from 1 so the second run failed with duplicate values.

The idea is to have the ability to set the count in a given value, also to let generate a random one:

export default class Fixture<T> {
  constructor(builders: BuilderGeneratorFunction<T>[], extendFixture: Array<Fixture<T>>, instanceCount: number = 1) {
    this.instanceCount = instanceCount;
    this.builders = builders;
    

    if (extendFixture.length > 0) {
      this.builders.push(...extendFixture.map(fixture => fixture.builders).flat());
    }
  }

  // ...
  withInstanceCount(count: number): Fixture<T> {
     const fixture = new Fixture(this.builders, [], count);
  }

  withRandomCount(digits: number = 6): Fixture<T> {
     return this.withInstanceCount(Math.floor(Math.random() * Math.pow(10, n))
  }

You can use it as:

const userFixture = defineFixture<User>(t => {
  t.id.asNumber();  // id field will be numerical value that increments as you create user objects
  t.firstName.asString(); 
  t.lastName.asString();
}).withRandomCount(3);

I can provide a PR

Charly-xepelin avatar Oct 01 '24 13:10 Charly-xepelin