QA Interview Hub · Knowledge base · Quizzes · Українська

Patterns › Builder and Test Data Builder

A Builder with faker, determinism and when a Builder is unnecessary

Faker in a builder is needed first of all for uniqueness of data across tests and workers, not for realism. Defaults are created per instance, and values the test asserts on are set explicitly. To reproduce a failure the faker.seed value is written to the report, but one seed for the whole run brings the conflicts back. For an object with two or three fields a Builder is unnecessary.

Patterns · Test Data Builder

A test failed on a name with an apostrophe, and on rerun the data is different. How to reproduce the failure?

A builder with random defaults works well under a parallel run: every test gets a unique user and does not conflict with its neighbours. But randomness has a cost. In an overnight run a bug vanished because the name O'Brien was not generated again, and the investigation came down to the words "it happened once". This lesson shows how to keep random data under control, when faker is needed and when a Builder is not needed at all.

How it works and why. The @faker-js/faker library generates plausible values: names, emails, addresses. Its main benefit in this context is not realism but uniqueness: two tests in different workers will not create two users with the same email, and building data needs no coordination. A fixed email in a builder would give an "already registered" conflict in the second test. The main risk is non-reproducibility: a test that fails only on some values must be rerunnable with the same ones.

Where the default lives

Wrong

A module constant

One email for the whole worker. The second test gets the same one and the system answers that such a user already exists.

Right

A class field

The value is created on every new. Each test has its own user.

Figure 1. Defaults must be created per instance, not per module.

Why a seed is needed

Run 1: seed 481516name "O’Brien": the test is redRerun without a seedanother name: green, the bug vanishedRerun with SEED=481516the same name: red, the bug is visible
Figure 2. A seed recorded in the report turns “it happened once” into a repeatable bug.

Example: a builder on faker. The starting point: defaults made a module constant, supposedly "to be more economical".

// one email for the whole worker: the second test gets "already registered"
const DEFAULT_USER = {
  email: faker.internet.email(),
  firstName: faker.person.firstName(),
};

export class UserBuilder {
  private data = { ...DEFAULT_USER };
  // ...
}

The constant is evaluated once when the module loads. All tests of a worker share the same email and their independence is gone. The fix is a class field. Four important places are marked.

import { faker } from '@faker-js/faker';

export class UserBuilder {
  // a class field: a new value on every new UserBuilder()
1  private data: NewUser = {
2    email: faker.internet.email({ provider: 'example.com' }),
    firstName: faker.person.firstName(),
    password: 'Str0ng!Pass',
  };

3  withEmail(email: string) {
    this.data.email = email;
    return this;
  }

4  build(): NewUser {
    return { ...this.data };
  }
}
  1. A class field is evaluated when an instance is created, so every new gives new values.
  2. The domain example.com is reserved for examples: test emails do not reach real mailboxes. Without the parameter faker takes real mail services.
  3. A test that checks the email sets it explicitly: withEmail.
  4. build() returns a copy so the builder can be reused.

Faker does not fit values the check depends on. If a test checks an amount or a field length, the value is set explicitly and not taken from a generator: otherwise the test checks a random number and fails only sometimes.

Reproducibility. faker.seed(n) makes the sequence of values deterministic: with the same seed and library version the same calls give the same values. That is why the seed is written into the report: then a failure is reproduced with a command that has SEED=….

export const test = base.extend<{ seed: number }>({
  seed: [
    async ({}, use, testInfo) => {
      const seed = Number(process.env.SEED) || Math.floor(Math.random() * 1e9);
      faker.seed(seed);
      // the seed is visible in the report: a failure can be reproduced
      testInfo.annotations.push({ type: 'seed', description: String(seed) });
      await use(seed);
    },
    { auto: true },
  ],
});

Here an auto fixture sets a new random seed before each test and writes it into the report annotations. A failure is reproduced by running only the failed test with its seed: SEED=… npx playwright test -g "test name". The reason for the limit: the fixture calls faker.seed before every test, so with a fixed SEED every test, in one worker or in several, generates the same users and collides on exactly the conflict faker was meant to remove. The values also depend on the faker version, so after a library upgrade an old seed may produce other data.

Limits and alternatives. A builder is not always needed. For an object with two or three fields a function with Partial is enough:

// two or three fields: a function with Partial instead of a class
export const makeUser = (o: Partial<NewUser> = {}): NewUser => ({
  email: 'qa+' + crypto.randomUUID() + '@example.com',
  password: 'Str0ng!Pass',
  ...o,
});

const user = makeUser({ email: 'dup@example.com' });

In TypeScript the object spread (...o) does much of what needs a Builder in Java. In an interview exactly this awareness sounds good, not "I make builders everywhere". Uniqueness does not always need faker: crypto.randomUUID() gives a unique value without a dependency, but a name made from it is unreadable. Faker is justified when data must look real (long names, diacritics, apostrophes), because such values catch form bugs.

Common mistakes.

  • Defaults in a module constant: all tests get one user and parallel runs conflict.
  • A random value in a field the test checks: the test fails only on some values and the cause is hard to find.
  • Generated data not logged and no seed: a failure that showed once cannot be reproduced.
  • A fixed seed for the whole run: every test, even in one worker, generates the same "unique" values and conflicts return.
  • Faker with real mail domains: test emails go to other people's mailboxes. Use example.com.

Check yourself

A builder creates a user with faker.internet.email() in a class field. A test failed on a specific value. How to guarantee that a rerun gives the same data?

Answer

Record the seed: call faker.seed(seed) before the test and print the seed into the report or annotations, and on rerun pass the same seed. Without a record, random values cannot be reproduced. Rerun only this test: with a fixed seed every test generates the same data.

For an object with two fields a developer wrote a 40-line Builder class. What to replace it with and why?

Answer

A function with Partial: makeUser({ email }). It is shorter and fully typed, and a spread with overrides gives the same as fluent methods. A Builder is justified for objects with many fields and variations where a domain language is needed.

In an interview. Junior: For unique fields I use faker, and values the test checks I set explicitly. I log the data so a failure can be reproduced. For simple objects I take a factory function with Partial, because a Builder is excessive there. Middle/Senior: Defaults per instance, not per module. I write the seed into the report and can repeat a failure with SEED, running only the failed test: with one seed for the whole run the tests collide again. I use a reserved domain for emails. A Builder is justified only for complex objects with domain methods.

More articles in this chapter