Test Data and Fixtures
Have you ever seen tests with random hardcoded data scattered everywhere? It makes tests hard to read and even harder to maintain. Good test data patterns save you from that mess.
Here is the thing. Test data should be predictable, readable, and easy to change. Let me show you the patterns that work.
Inline Test Data
For simple tests, just put the data right in the test. Keep it small and obvious.
it('validates email format', () => {
expect(validateEmail('alice@example.com')).toBe(true);
expect(validateEmail('invalid')).toBe(false);
expect(validateEmail('')).toBe(false);
});
This works when you have a few simple values. But when your test data gets more complex, inline data gets messy fast.
Factory Functions
A factory function creates test data with sensible defaults. You call it in your test and override only what you need.
function createUser(overrides = {}) {
return {
id: 1,
name: 'Alice',
email: 'alice@example.com',
age: 25,
...overrides
};
}
it('creates user with defaults', () => {
const user = createUser();
expect(user.name).toBe('Alice');
});
it('creates user with custom name', () => {
const user = createUser({ name: 'Bob' });
expect(user.name).toBe('Bob');
expect(user.email).toBe('alice@example.com');
});
Fixture Files
For larger test data, create separate fixture files. This keeps your test files clean.
// fixtures/users.js
module.exports = [
{ id: 1, name: 'Alice', role: 'admin' },
{ id: 2, name: 'Bob', role: 'user' },
{ id: 3, name: 'Charlie', role: 'moderator' }
];
// In your test file
const users = require('./fixtures/users');
it('filters admin users', () => {
const admins = users.filter(u => u.role === 'admin');
expect(admins.length).toBe(1);
expect(admins[0].name).toBe('Alice');
});
Keep It Minimal
Only include the data your test actually needs. Do not create huge objects when you only check one property. Minimal data means your test stays focused and readable.
Try it Yourself →Key Takeaways
- Inline data works for simple, small test cases
- Factory functions create reusable test data with defaults
- Fixture files store larger test data outside your test files
- Only include the data your test needs, keep it minimal
- Use spread operators in factories to override specific fields