Fixture 생성 개요
createFixtureLoader
타입 안전한 정의 자동완성 지원
재사용 가능
한 번 정의 여러 테스트 공유
관계 처리
BelongsTo 자동 해결 중첩된 데이터
선택적 로딩
필요한 것만 빠른 테스트
createFixtureLoader
기본 구조
// 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 이름: 로더 함수
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);
},
});
타입 정의
/**
* Fixture Loader Factory
*
* 테스트에서 사용할 fixture를 로드하는 함수를 생성
*/
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]()])),
);
};
}
- 타입 안전: TypeScript가 fixture 이름과 반환 타입을 추론
- 병렬 로딩:
Promise.all로 여러 fixture 동시 로드 - 선택적: 필요한 fixture만 로드
실전 예제
단순 Fixtures
// api/src/testing/fixture.ts
import { createFixtureLoader } from "sonamu/test";
import { UserModel } from "../application/user/user.model";
export const loadFixtures = createFixtureLoader({
// 일반 사용자
guestUser: async () => {
const [userId] = await UserModel.save([{
username: "guest",
email: "guest@example.com",
password: "password",
role: "guest",
}]);
return UserModel.findById("A", userId);
},
// 프리미엄 사용자
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);
},
// 관리자
adminUser: async () => {
const [userId] = await UserModel.save([{
username: "admin",
email: "admin@example.com",
password: "password",
role: "admin",
}]);
return UserModel.findById("A", userId);
},
});
관계가 있는 Fixtures
// 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({
// 기본 사용자
author: createAuthor,
// 작성자와 그의 게시글을 함께 반환
authorWithPost: async () => {
const author = await createAuthor();
const post = await createPost(author.id);
return { author, post };
},
// 작성자의 댓글이 달린 게시글
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 };
},
});
여러 데이터 생성
export const loadFixtures = createFixtureLoader({
// 10명의 사용자
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;
},
// 사용자와 그의 게시글들
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 };
},
});
복잡한 시나리오
export const loadFixtures = createFixtureLoader({
// 완전한 블로그 시나리오
blogScenario: async () => {
// 1. 작성자 생성
const [authorId] = await UserModel.save([{
username: "author",
email: "author@example.com",
password: "password",
}]);
const author = await UserModel.findById("A", authorId);
// 2. 독자들 생성
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. 게시글 생성
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. 댓글 생성
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(),
};
},
});
테스트에서 사용하기
기본 사용
// 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 () => {
// Fixtures 로드
const { authorWithPost } = await loadFixtures(["authorWithPost"]);
const { author, post } = authorWithPost;
// 테스트
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);
});
타입 안전성
test("type-safe fixture usage", async () => {
// ✅ IDE가 fixture 이름 자동완성 제공
const { author, authorWithPost } = await loadFixtures(["author", "authorWithPost"]);
// ✅ 타입 추론
author.username; // string
authorWithPost.post.title; // string
// ❌ 존재하지 않는 fixture
const { invalid } = await loadFixtures(["invalid"]); // 타입 에러!
});
선택적 로딩
test("필요한 fixture만 로드", async () => {
// 필요한 것만
const { author } = await loadFixtures(["author"]);
// authorWithPost는 로드하지 않음 → 생성 비용 절약
});
test("여러 fixture 동시 로드", async () => {
// 병렬로 로드 (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");
});
베스트 프랙티스
1. 명확한 이름
// ✅ 올바른 방법: 용도가 명확한 이름
export const loadFixtures = createFixtureLoader({
adminUser: async () => {
/* ... */
},
guestUser: async () => {
/* ... */
},
publishedPost: async () => {
/* ... */
},
draftPost: async () => {
/* ... */
},
premiumSubscription: async () => {
/* ... */
},
});
// ❌ 잘못된 방법: 불명확한 이름
export const loadFixtures = createFixtureLoader({
user1: async () => {
/* ... */
},
user2: async () => {
/* ... */
},
post1: async () => {
/* ... */
},
thing: async () => {
/* ... */
},
});
2. 최소 데이터
// ✅ 올바른 방법: 필수 필드만
export const loadFixtures = createFixtureLoader({
basicUser: async () => {
const [userId] = await UserModel.save([{
username: "user",
email: "user@example.com",
password: "password",
// 필수 필드만
}]);
return UserModel.findById("A", userId);
},
});
// ❌ 잘못된 방법: 불필요한 필드까지
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: {
/* 복잡한 객체 */
},
// 테스트에 필요하지 않은 필드들
}]);
return UserModel.findById("A", userId);
},
});
3. Fixture 재사용
// ✅ 올바른 방법: 생성 로직은 일반 헬퍼 함수로 공유
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를 호출하지 말고 헬퍼 함수로 공유하세요. 로더 객체가 자신의 초기화식에서 자기 자신을 참조하게 되어 TypeScript strict 모드에서 오류(TS7022)가 납니다.
4. 일관된 구조
// ✅ 올바른 방법: 일관된 네이밍과 구조
export const loadFixtures = createFixtureLoader({
// 사용자 관련
adminUser: async () => {
/* ... */
},
guestUser: async () => {
/* ... */
},
premiumUser: async () => {
/* ... */
},
// 게시글 관련
publishedPost: async () => {
/* ... */
},
draftPost: async () => {
/* ... */
},
// 시나리오
blogScenario: async () => {
/* ... */
},
forumScenario: async () => {
/* ... */
},
});
고급 패턴
팩토리 함수
// 동적으로 fixture 생성
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"),
});
주의사항
Fixture 작성 시 주의사항: 1. Transaction 기반: 각 테스트마다 자동 롤백됨 2. 최소
데이터: 테스트에 필요한 최소한의 데이터만 생성 3. 독립성: Fixture는 서로 독립적이어야 함 4.
재사용: 공통 fixture를 적극 활용 5. 명확한 이름: fixture 이름은 용도를 명확하게 표현
다음 단계
테스트 DB
테스트 DB 설정
Fixture 로딩
프로덕션 데이터 가져오기
Fixture 동기화
Fixture → Test DB
테스트 헬퍼
createFixtureLoader 상세