Creating Fixtures Overview
createFixtureLoader
Type-safe definition Auto-completion support
Reusable
Define once Share across tests
Relation Handling
Auto BelongsTo resolution Nested data
Selective Loading
Load only what you need Fast tests
createFixtureLoader
Basic Structure
// api/src/testing/fixture.ts
import { createFixtureLoader } from "sonamu/test";
import { UserModel } from "../application/user/user.model";
import { PostModel } from "../application/post/post.model";
export const loadFixtures = createFixtureLoader({
// Fixture name: loader function
user01: async () => {
const [userId] = await UserModel.save([{
username: "john",
email: "john@example.com",
password: "password123",
}]);
return UserModel.findById("A", userId);
},
admin: async () => {
const [userId] = await UserModel.save([{
username: "admin",
email: "admin@example.com",
password: "admin123",
role: "admin",
}]);
return UserModel.findById("A", userId);
},
});
Type Definition
/**
* Fixture Loader Factory
*
* Creates a function that loads fixtures for use in tests
*/
type FixtureLoaderValue = object | string | number | boolean | bigint | symbol | null | undefined;
export function createFixtureLoader<T extends Record<string, () => Promise<FixtureLoaderValue>>>(
loaders: T,
) {
return async function loadFixtures<K extends keyof T>(
names: K[],
): Promise<{ [P in K]: Awaited<ReturnType<T[P]>> }> {
return Object.fromEntries(
await Promise.all(names.map(async (name) => [name, await loaders[name]()])),
);
};
}
- Type-safe: TypeScript infers fixture names and return types
- Parallel loading: Multiple fixtures loaded simultaneously with
Promise.all - Selective: Load only needed fixtures
Practical Examples
Simple Fixtures
// api/src/testing/fixture.ts
import { createFixtureLoader } from "sonamu/test";
import { UserModel } from "../application/user/user.model";
export const loadFixtures = createFixtureLoader({
// Guest user
guestUser: async () => {
const [userId] = await UserModel.save([{
username: "guest",
email: "guest@example.com",
password: "password",
role: "guest",
}]);
return UserModel.findById("A", userId);
},
// Premium user
premiumUser: async () => {
const [userId] = await UserModel.save([{
username: "premium",
email: "premium@example.com",
password: "password",
role: "premium",
subscription_expires_at: new Date("2025-12-31"),
}]);
return UserModel.findById("A", userId);
},
// Admin
adminUser: async () => {
const [userId] = await UserModel.save([{
username: "admin",
email: "admin@example.com",
password: "password",
role: "admin",
}]);
return UserModel.findById("A", userId);
},
});
Fixtures with Relations
// api/src/testing/fixture.ts
import { createFixtureLoader } from "sonamu/test";
import { CommentModel } from "../application/comment/comment.model";
import { PostModel } from "../application/post/post.model";
import { UserModel } from "../application/user/user.model";
async function createAuthor() {
const [userId] = await UserModel.save([
{ username: "author", email: "author@example.com", password: "password" },
]);
return UserModel.findById("A", userId);
}
async function createPost(authorId: number) {
const [postId] = await PostModel.save([
{ title: "Author's First Post", content: "This is the content", author_id: authorId },
]);
return PostModel.findById("A", postId);
}
export const loadFixtures = createFixtureLoader({
// Base user
author: createAuthor,
// Author and their post, returned together
authorWithPost: async () => {
const author = await createAuthor();
const post = await createPost(author.id);
return { author, post };
},
// Post with a comment by its author
postWithComment: async () => {
const author = await createAuthor();
const post = await createPost(author.id);
const [commentId] = await CommentModel.save([
{ content: "Great post!", post_id: post.id, author_id: author.id },
]);
const comment = await CommentModel.findById("A", commentId);
return { author, post, comment };
},
});
Creating Multiple Data
export const loadFixtures = createFixtureLoader({
// 10 users
users10: async () => {
const users = [];
for (let i = 1; i <= 10; i++) {
const [userId] = await UserModel.save([{
username: `user${i}`,
email: `user${i}@example.com`,
password: "password",
}]);
const user = await UserModel.findById("A", userId);
users.push(user);
}
return users;
},
// User with their posts
userWith5Posts: async () => {
const [userId] = await UserModel.save([{
username: "blogger",
email: "blogger@example.com",
password: "password",
}]);
const user = await UserModel.findById("A", userId);
const posts = [];
for (let i = 1; i <= 5; i++) {
const [postId] = await PostModel.save([{
title: `Post ${i}`,
content: `Content ${i}`,
author_id: user.id,
}]);
const post = await PostModel.findById("A", postId);
posts.push(post);
}
return { user, posts };
},
});
Complex Scenarios
export const loadFixtures = createFixtureLoader({
// Complete blog scenario
blogScenario: async () => {
// 1. Create author
const [authorId] = await UserModel.save([{
username: "author",
email: "author@example.com",
password: "password",
}]);
const author = await UserModel.findById("A", authorId);
// 2. Create readers
const [[reader1Id], [reader2Id]] = await Promise.all([
UserModel.save([{
username: "reader1",
email: "reader1@example.com",
password: "password",
}]),
UserModel.save([{
username: "reader2",
email: "reader2@example.com",
password: "password",
}]),
]);
// 3. Create post
const [postId] = await PostModel.save([{
title: "Popular Post",
content: "This post has many comments",
author_id: author.id,
}]);
const post = await PostModel.findById("A", postId);
// 4. Create comments
const comments = await Promise.all([
CommentModel.save([{
content: "First comment",
post_id: post.id,
author_id: reader1Id,
}]),
CommentModel.save([{
content: "Second comment",
post_id: post.id,
author_id: reader2Id,
}]),
CommentModel.save([{
content: "Author reply",
post_id: post.id,
author_id: author.id,
}]),
]);
return {
author,
readerIds: [reader1Id, reader2Id],
post,
commentIds: comments.flat(),
};
},
});
Using in Tests
Basic Usage
// api/src/application/post/post.model.test.ts
import { bootstrap, test } from "sonamu/test";
import { expect, vi } from "vitest";
import { PostModel } from "./post.model";
import { loadFixtures } from "../../testing/fixture";
bootstrap(vi);
test("get author's posts", async () => {
// Load fixtures
const { authorWithPost } = await loadFixtures(["authorWithPost"]);
const { author, post } = authorWithPost;
// Test
const posts = await PostModel.getPuri("r")
.table("posts")
.select({ id: "posts.id" })
.where("posts.author_id", author.id);
expect(posts).toHaveLength(1);
expect(posts[0].id).toBe(post.id);
});
Type Safety
test("type-safe fixture usage", async () => {
// ✅ IDE provides fixture name auto-completion
const { author, authorWithPost } = await loadFixtures(["author", "authorWithPost"]);
// ✅ Type inference
author.username; // string
authorWithPost.post.title; // string
// ❌ Non-existent fixture
const { invalid } = await loadFixtures(["invalid"]); // Type error!
});
Selective Loading
test("load only needed fixtures", async () => {
// Only what's needed
const { author } = await loadFixtures(["author"]);
// authorWithPost not loaded → creation cost saved
});
test("load multiple fixtures simultaneously", async () => {
// Loaded in parallel (Promise.all)
const { author, premiumUser, adminUser } = await loadFixtures([
"author",
"premiumUser",
"adminUser",
]);
expect(author.role).toBe("user");
expect(premiumUser.role).toBe("premium");
expect(adminUser.role).toBe("admin");
});
Best Practices
1. Clear Names
// ✅ Correct: Names with clear purpose
export const loadFixtures = createFixtureLoader({
adminUser: async () => {
/* ... */
},
guestUser: async () => {
/* ... */
},
publishedPost: async () => {
/* ... */
},
draftPost: async () => {
/* ... */
},
premiumSubscription: async () => {
/* ... */
},
});
// ❌ Wrong: Unclear names
export const loadFixtures = createFixtureLoader({
user1: async () => {
/* ... */
},
user2: async () => {
/* ... */
},
post1: async () => {
/* ... */
},
thing: async () => {
/* ... */
},
});
2. Minimal Data
// ✅ Correct: Only required fields
export const loadFixtures = createFixtureLoader({
basicUser: async () => {
const [userId] = await UserModel.save([{
username: "user",
email: "user@example.com",
password: "password",
// Only required fields
}]);
return UserModel.findById("A", userId);
},
});
// ❌ Wrong: Unnecessary fields
export const loadFixtures = createFixtureLoader({
complexUser: async () => {
const [userId] = await UserModel.save([{
username: "user",
email: "user@example.com",
password: "password",
bio: "Very long bio...",
avatar: "https://...",
preferences: {
/* complex object */
},
// Fields not needed for test
}]);
return UserModel.findById("A", userId);
},
});
3. Fixture Reuse
// ✅ Correct: Share creation logic through plain helper functions
async function createUser() {
const [userId] = await UserModel.save([
{ username: "user", email: "user@example.com", password: "password" },
]);
return UserModel.findById("A", userId);
}
async function createPost(authorId: number) {
const [postId] = await PostModel.save([
{ title: "Post", content: "Content", author_id: authorId },
]);
return PostModel.findById("A", postId);
}
export const loadFixtures = createFixtureLoader({
user: createUser,
userPost: async () => {
const user = await createUser();
const post = await createPost(user.id);
return { user, post };
},
userPostComment: async () => {
const user = await createUser();
const post = await createPost(user.id);
const [commentId] = await CommentModel.save([
{ content: "Comment", post_id: post.id, author_id: user.id },
]);
const comment = await CommentModel.findById("A", commentId);
return { user, post, comment };
},
});
loadFixtures inside a loader: the loader object would reference itself in its own initializer, which TypeScript rejects in strict mode (TS7022).
4. Consistent Structure
// ✅ Correct: Consistent naming and structure
export const loadFixtures = createFixtureLoader({
// User related
adminUser: async () => {
/* ... */
},
guestUser: async () => {
/* ... */
},
premiumUser: async () => {
/* ... */
},
// Post related
publishedPost: async () => {
/* ... */
},
draftPost: async () => {
/* ... */
},
// Scenarios
blogScenario: async () => {
/* ... */
},
forumScenario: async () => {
/* ... */
},
});
Advanced Patterns
Factory Functions
// Dynamically create fixtures
function createUserFixture(username: string, role: string) {
return async () => {
const [userId] = await UserModel.save([{
username,
email: `${username}@example.com`,
password: "password",
role,
}]);
return UserModel.findById("A", userId);
};
}
export const loadFixtures = createFixtureLoader({
adminUser: createUserFixture("admin", "admin"),
guestUser: createUserFixture("guest", "guest"),
moderatorUser: createUserFixture("moderator", "moderator"),
});
Cautions
Cautions when writing fixtures: 1. Transaction-based: Auto-rollback after each test 2.
Minimal data: Create only minimum data needed for test 3. Independence: Fixtures should be
independent of each other 4. Reuse: Actively utilize common fixtures 5. Clear names:
Fixture names should clearly express purpose
Next Steps
Test DB
Test DB setup
Loading Fixtures
Import production data
Syncing Fixtures
Fixture → Test DB
Test Helpers
createFixtureLoader details