intermediate
Test data builders and fixtures
Use builders, factories, and fixtures to express relevant data while avoiding global mutable setup that couples unrelated tests.
Builders and factories express only the fields relevant to each test—`UserBuilder().withRole('admin').build()`—avoiding 50-line object literals. Fixtures load shared baseline data; prefer function-scoped setup over global beforeAll that couples unrelated tests.
Factories should default valid data and allow overrides; keep randomness explicit and seeded.
On interviews: show how a builder reduced duplication without hiding the behavior under test.
Common pitfalls: mega-fixtures every test mutates, builders with hidden side effects (auto-insert DB), and copy-paste literals diverging from production schema.
The trade-off is readability versus indirection—builders help until you need to read three files to understand one test.
Checklist:
- Defaults valid; override only differing fields.
- Scope fixtures to describe blocks or tests.
- Align factory shapes with API/schema types.