A test data factory is a function with valid defaults and an overrides: Partial<T> parameter, where the passed value wins as overrides are spread last. Two traps: the spread is shallow, so a nested object is replaced whole, and an explicit undefined in overrides erases a default. A pure data factory has no side effects; one that creates an entity through the API is a precondition with cleanup in a fixture.
Patterns · Factory
createCard is used in forty tests, and in one the date somehow vanished. Where does undefined come from?
A framework has a createCard function used in forty tests. In the forty-first a developer passes createCard({ expiry: maybeDate }), where the variable is sometimes empty, and the test suddenly gets a card with no expiry. The simple Factory pattern has two subtle traps: an explicit undefined and a shallow spread. This lesson shows a factory function with Partial, a factory that creates entities through the API, and these traps.
How it works and why. A Factory encapsulates object creation. In TypeScript tests it is most often a plain function with defaults and a parameter overrides: Partial<T>. Defaults give a valid object, and overrides change only what matters for the test. The Partial type forbids passing a field that is not in the model, so a typo in a name is caught by the compiler. This is shorter than a Builder and needs no class, so for simple and medium objects a factory is usually the first choice.
The key point is the order: in { ...defaults, ...overrides } the right side wins over the left. So overrides go last and defaults first.
How defaults and overrides merge
Figure 1. What is passed wins over the default. An explicit undefined is “passed” too: it erases the default.
Where to create an entity
Wrong
An API call with cleanup in the test
The deletion sits after expect. The test failed and the account stayed in the system.
Right
An API factory in a fixture
Creation and deletion together. The deletion runs after a failed test too.
Figure 2. A factory that changes the system is also responsible for cleaning up.
Example: a simple factory. Four important places are marked.
1exportfunctioncreateCard(overrides: Partial<Card> = {}): Card {
return {
2 number: '4111111111111111',
holder: 'TEST USER',
expiry: '12/30',
cvv: '123',
// overrides last: they win over the defaults3 ...overrides,
};
}
4const expired = createCard({ expiry: '01/20' });
const other = createCard({ holder: 'ANNA K' });
overrides: Partial<Card> with an empty default: a call without arguments gives a valid card.
Defaults are valid values; 4111… is a well-known test card number, not a real one.
Spread last: what is passed wins over the defaults.
The test names only what matters: the card is expired or has another holder.
Two rules work here: the function returns a new object every time (the literal is created on every call), and the type does not allow passing { expirey: '01/20' }. Now the traps.
Trap 1: spread is shallow. If an object contains a nested one, { ...base, ...overrides } replaces the nested one whole: createUser({ address: { city: 'Lviv' } }) in JavaScript leaves the user without street and zip, and with Partial<User> it does not even compile. Nested parts are merged separately:
typeUserOverrides = Omit<Partial<User>, 'address'> & {
address?: Partial<User['address']>;
};
exportfunctioncreateUser(o: UserOverrides = {}): User {
const base: User = {
email: 'qa+' + crypto.randomUUID() + '@example.com',
address: { city: 'Kyiv', street: 'Main 1', zip: '01001' },
};
return {
...base,
...o,
// spread is shallow: without this the nested object is replaced whole
address: { ...base.address, ...o.address },
};
}
createUser({ address: { city: 'Lviv' } }); // street, zip kept
Partial is shallow too: Partial<User> requires a full address, so the nested field gets its own Partial.
For deep structures there are ready-made merge functions (for example, lodash.merge), but they treat arrays differently, so in test data an explicit merge of nested fields is more reliable.
Trap 2: explicit undefined. If you pass { expiry: undefined }, that key exists in the overrides object and spread rewrites the default to undefined. It happens when a value comes from a variable that is sometimes empty. The error is subtle: the type Partial<Card> allows it, because an optional field may be undefined.
// filter out undefined so it does not erase the defaultsconst defined = <T extends object>(o: T): T =>
Object.fromEntries(
Object.entries(o).filter(([, v]) => v !== undefined),
) as T;
return { ...base, ...defined(overrides) };
If a test deliberately wants "a field without a value", it should do so explicitly (for example, createCard({ cvv: '' }) for an empty string) so as not to rely on undefined.
A factory that creates an entity through the API. The second form not only builds an object but also creates it in the system. It is convenient for preconditions but needs cleanup, so it is wrapped in a Playwright fixture:
exportasyncfunctioncreateAccountViaApi(
request: APIRequestContext,
overrides: Partial<NewAccount> = {},
): Promise<Account> {
const res = await request.post('/api/accounts', {
data: { currency: 'EUR', ...overrides },
});
expect(res.ok()).toBeTruthy();
return (await res.json()) asAccount;
}
// in a fixture: cleanup is guaranteed even after a failure
account: async ({ request }, use) => {
const account = awaitcreateAccountViaApi(request);
awaituse(account);
await request.delete('/api/accounts/' + account.id);
},
Limits and alternatives. A factory function is convenient while variations are few. When an object has many fields and tests need complex combinations, a Builder with domain methods is more expressive. If an object is used in one test and its fields are the point of the check, an explicit literal reads better than a factory (so-called DAMP). A factory that calls the API is already a precondition, not data: its place is in a fixture or App Actions, and a pure data factory stays pure and has no side effects.
Common mistakes.
Overrides before defaults ({ ...overrides, ...defaults }): defaults win and the passed value is ignored.
An explicit undefined in overrides: it erases the default and the test fails on a "missing" field.
A shallow spread for nested objects: the nested object is replaced whole and its other fields disappear.
A factory that returns one shared constant: a test changes it and the next ones get spoiled data.
A factory that creates through the API without cleanup: garbage piles up in the environment.
Check yourself
createCard({ expiry: maybeDate }) returns a card with expiry: undefined though the default is '12/30'. Why and what to change?
Answer
The key expiry is present in overrides with the value undefined, so the spread (...overrides) rewrites the default to undefined. Either do not pass the key when the value is empty, or filter out undefined in the factory before merging.
createUser({ address: { city: 'Lviv' } }) returns an address without street and zip. Why and how to fix it?
Answer
Spread is shallow: the address field from overrides replaces the default whole. The nested part must be merged separately: address: { ...base.address, ...o.address }, and then the fields not given stay from the defaults.
Related lessons: “Factory vs Builder and a Page Objects factory”, “Test Data Builder: the problem and the solution”, “Fixtures: DI built into Playwright Test”, “App Actions: preconditions without the UI”.
In an interview.Junior: For data I most often write factory functions with defaults and a Partial override: it is short and type-safe. Factories that create entities through the API I wrap in fixtures so cleanup is guaranteed. Middle/Senior: I keep overrides after defaults and remember two traps: spread is shallow, and an explicit undefined erases a default. I merge nested parts separately. A data factory is pure, without side effects, while one that calls the API is a precondition with cleanup in a fixture.
Factory vs Builder and a Page Objects factory
A factory and a Builder both create test data but describe a variation differently. A factory takes parameters in one call, a Builder assembles the object in a chain of domain methods. The choice follows complexity: a literal, a factory, a Builder, moving up only when the current one becomes awkward. A Builder can take its defaults from a factory, and a Page Objects factory in Playwright is usually replaced by fixtures.
Patterns · Factory
A Builder or a factory: when is a three-line function enough and when do you need a class?
A team argues: write a Builder for every object because "it is correct", or get by with functions. Both approaches solve the same task, creating test data, but differ in cost and expressiveness. A separate question is a Page Objects factory: is an App class with getters needed if Playwright has fixtures. This lesson gives a rule for choosing and shows where each option is justified.
How it works and why. A Factory and a Builder differ in how the test describes a variation. A factory takes parameters in one call: createCard({ expiry }). A Builder assembles the object in a chain: .withItems(3).paid(). For one or two changed fields a factory is shorter. When variations and related fields are many (an order with a list of items, discounts and statuses), a chain with domain names reads better than an object with a dozen parameters. The data is the same here; what differs is who carries the complexity: the test or the class.
Criterion
Factory
Builder
Call
one function
a chain of methods
Object
simple or medium
complex, many variations
Domain language
through parameters
through methods like paid()
Amount of code
minimal
more boilerplate
What to choose for data
Figure 1. Move up a step only when the current one has become inconvenient.
A default: a constant or a function
Wrong
A shared constant
One object for all tests. A test changes it and the next ones get spoiled data.
Right
A function that returns a new one
Every call gives a fresh object. One test mutating it harms nobody.
Figure 2. A factory always returns a new object.
Example: how they coexist. In practice they are combined: a Builder takes its defaults from a factory. Then defaults live in one place and the Builder adds only domain methods. Four important places are marked.
exportclassOrderBuilder {
1private data: Order = defaultOrder();
2withItems(n: number) {
this.data.items = Array.from({ length: n }, () => defaultItem());
returnthis;
}
3paid() {
this.data.status = 'paid';
returnthis;
}
build(): Order {
returnstructuredClone(this.data);
}
}
// defaults come from a factory: one source of truth4const order = newOrderBuilder().withItems(3).paid().build();
Defaults come from a factory: a single source of truth for a valid order.
A method describes a variation that has a parameter: the number of items.
A domain method for a state: paid() instead of withStatus('paid').
The call reads as a description: an order with three items, paid.
A danger shared by both approaches is shown below. A factory that returns one constant instead of a new object makes tests depend on each other:
// one constant: a test changes it and the next ones see the changeexportconst DEFAULT_CARD: Card = { number: '4111111111111111', cvv: '123' };
test('mutates', async () => {
DEFAULT_CARD.cvv = '000';
});
// a function: every call returns a new objectexportconst defaultCard = (): Card => ({ number: '4111111111111111', cvv: '123' });
The first variant works while no test changes the object. The longer a suite lives, the likelier somebody changes it. A function costs nothing, while this mistake shows up only with a particular execution order or a parallel run, when it is hard to find.
A Page Objects factory. Another meaning of the word: a class that creates Page Objects so that new is not written in every test.
exportclassApp {
constructor(privatereadonly page: Page) {}
get login() {
returnnewLoginPage(this.page);
}
get payments() {
returnnewPaymentsPage(this.page);
}
}
// dynamic: the page appeared inside the testconst [popup] = awaitPromise.all([
page.waitForEvent('popup'),
page.getByRole('link', { name: 'Help' }).click(),
]);
const help = newHelpPage(popup);
In Playwright this role is usually better played by fixtures: they are lazy, cleaned up after the test and typed (see the lesson on fixtures). A separate App class makes sense when pages must be created dynamically inside a test, for example after a new tab opens: we get a new page from the event and the page class is created from it, as in the second half of the example. A getter that creates a new object each time is safe, because a Page Object only holds lazy locators.
Limits and alternatives. A factory and a Builder are not needed if an object is used in one test and its fields are the point of the check: an explicit literal reads better (DAMP, "descriptive and meaningful phrases"). They should also not be added "just in case": a Builder class for a model that appeared yesterday and has three fields costs more than it gives. The right sequence: a literal; a factory once duplication becomes noise; a Builder once variations get complex.
Common mistakes.
A Builder for every model "by the rules": hundreds of lines of boilerplate for objects a literal would serve.
A factory with a long list of positional parameters (createUser(a, b, c, d, e)): the call cannot be read. Take one Partial object.
A shared constant instead of a function: one test's mutation poisons the others.
Merging data and side effects in one "factory": it both builds an object and calls the API, and it cannot be used without a network.
A separate Page Objects factory class that duplicates fixtures: two ways to do the same thing.
Check yourself
For a model with three fields used in two tests, a 60-line Builder is proposed. What do you advise?
Answer
A factory function with Partial or even a literal: for three fields a Builder costs more than it gives. A Builder is justified when fields and variations are many and a domain language (paid(), failed()) makes the test more expressive.
When does a separate Page Objects factory make sense despite fixtures?
Answer
When pages are created dynamically inside a test: for example, a click opened a new tab and the new page comes from the popup event. A fixture is created before the test, so for such a case the page class is created from the new page by hand or through a small App class.
Related lessons: “A test data factory”, “Test Data Builder: the problem and the solution”, “Fixtures: DI built into Playwright Test”, “DRY vs DAMP and KISS”.
In an interview.Junior: A Factory is one function for simple variations, a Builder is a fluent API for complex objects with a domain language. I usually replace a Page Objects factory in Playwright with fixtures. Middle/Senior: I choose by complexity: a literal, a factory, a Builder, and I move up a step only when the current one is inconvenient. A Builder takes defaults from a factory so there is one source of truth. A default is always a function returning a new object, never a constant. A separate page class is justified for dynamically created pages, such as a popup.