2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

はじめに

Prismaを使ったプロジェクトでテストを書こうとしたとき、最初に悩んだのが「DBをどう扱うか」という問題だった。

  • Prismaクライアントをモックする?
  • テスト用DBに直接書く?
  • テストごとにDBをリセット?

そんなときに見つけたのが jest-prisma と prisma-fabbrica の組み合わせ。試してみたら「これだ」と思ったので紹介したい。

何が嬉しいのか

一言でいうと:

  • jest-prisma:テストごとにトランザクションを張って自動ロールバックしてくれる → テストが互いに干渉しない
  • prisma-fabbrica:Prismaスキーマからテストデータのファクトリを自動生成してくれる → テストデータのセットアップが楽になる

この2つを組み合わせると、実際のDBを使いながら、テストが綺麗に分離できる構成が手軽に作れる。

今回作ったサンプル

NestJS + Prisma で簡単なブログAPIを作り、そのサービス層のテストを書く構成にした。

スキーマ

model User {
  id        Int       @id @default(autoincrement())
  email     String    @unique
  name      String
  articles  Article[]
  createdAt DateTime  @default(now())
}

model Article {
  id        Int      @id @default(autoincrement())
  title     String
  body      String
  published Boolean  @default(false)
  author    User     @relation(fields: [authorId], references: [id], onDelete: Cascade)
  authorId  Int
  tags      Tag[]
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

model Tag {
  id        Int       @id @default(autoincrement())
  name      String    @unique
  articles  Article[]
  createdAt DateTime  @default(now())
}

User → Article → Tag というリレーションがある。テストでリレーションを含むデータを作ると一気に面倒になるので、ここでファクトリが活きてくる。

ファクトリを定義する

ファクトリの書き方はこんな感じ。

import {
  defineArticleFactory,
  defineTagFactory,
  defineUserFactory,
} from '../__generated__/fabbrica';

export const UserFactory = defineUserFactory({
  defaultData: ({ seq }) => ({
    email: `user-${seq}@example.com`,
    name: `User ${seq}`,
  }),
});

export const TagFactory = defineTagFactory({
  defaultData: ({ seq }) => ({
    name: `tag-${seq}`,
  }),
});

export const ArticleFactory = defineArticleFactory({
  defaultData: ({ seq }) => ({
    title: `Article ${seq}`,
    body: `Body ${seq}`,
    author: UserFactory,  // リレーションもここで指定できる
  }),
});

ポイントは seq。複数レコードを作るときに連番が振られるので、email のような UNIQUE 制約があるフィールドでも衝突しない。

また ArticleFactory の author に UserFactory を渡しているのもうれしいところで、ArticleFactory.create() するだけで User も一緒に作られる。

テストを書く

NestJS の DI コンテナに差し込む

NestJS を使っている場合、PrismaService を jestPrisma.client で差し替える必要がある。

beforeEach(async () => {
  const module: TestingModule = await Test.createTestingModule({
    providers: [ArticleService, PrismaService],
  })
    .overrideProvider(PrismaService)
    .useValue(jestPrisma.client)  // ここで差し替える
    .compile();

  service = module.get(ArticleService);
});

実際のテスト

it('creates a draft article with author and tags', async () => {
  const author = await UserFactory.create({
    email: 'alice@example.com',
    name: 'Alice',
  });
  const nestTag = await TagFactory.create({ name: 'nestjs' });
  const prismaTag = await TagFactory.create({ name: 'prisma' });

  const article = await service.createDraft({
    authorId: author.id,
    tagIds: [nestTag.id, prismaTag.id],
    title: 'Testing NestJS with Prisma',
    body: 'Use real database transactions in tests.',
  });

  expect(article.published).toBe(false);
  expect(article.author.email).toBe('alice@example.com');
  expect(article.tags.map((tag) => tag.name).sort()).toEqual(['nestjs', 'prisma']);
});

UserFactory.create() や TagFactory.create() でサクッとデータを作れる。

このテストが終わるとトランザクションが自動でロールバックされるので、次のテストには一切影響しない。

まとめ

Prismaのテストで悩んでいた「DBをどう扱うか」は、この2つの組み合わせでほぼ解決した。

ファクトリでデータを用意して実際のDBに対してテストを書くだけ、という書き味の良さが特に印象に残った。

今回は基本的な使い方のみだったので、応用的な使い方も今後試して記事にしたい。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?