A test data factory
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
Where to create an entity
An API call with cleanup in the test
The deletion sits after expect. The test failed and the account stayed in the system.
An API factory in a fixture
Creation and deletion together. The deletion runs after a failed test too.
Example: a simple factory. Four important places are marked.
1export function createCard(overrides: Partial<Card> = {}): Card {
return {
2 number: '4111111111111111',
holder: 'TEST USER',
expiry: '12/30',
cvv: '123',
// overrides last: they win over the defaults
3 ...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:
type UserOverrides = Omit<Partial<User>, 'address'> & {
address?: Partial<User['address']>;
};
export function createUser(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 defaults
const 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:
export async function createAccountViaApi(
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()) as Account;
}
// in a fixture: cleanup is guaranteed even after a failure
account: async ({ request }, use) => {
const account = await createAccountViaApi(request);
await use(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
undefinedin 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.