統合テスト
統合テストは、プログラムの個々の部分がどのように連携して動作するかをテストすることに焦点を当てています。データベースを使用するアプリケーションのコンテキストでは、統合テストは通常、データベースが利用可能であり、テスト対象のシナリオに都合の良いデータが含まれている必要があります。
現実世界の環境をシミュレートする1つの方法は、Dockerを使用して、データベースといくつかのテストデータをカプセル化することです。これはテストとともに起動および破棄できるため、本番データベースから隔離された環境として動作します。
注: このブログ記事では、統合テスト環境のセットアップと実際のデータベースに対する統合テストの作成に関する包括的なガイドを提供しており、このトピックを探求しようとしている人にとって貴重な洞察を提供しています。
前提条件
このガイドは、マシンにDockerとDocker Composeがインストールされており、プロジェクトに Jest
がセットアップされていることを前提としています。
以下の e コマーススキーマは、ガイド全体で使用されます。これは、他のドキュメントで使用されている従来の User
モデルと Post
モデルとは異なります。主に、ブログに対して統合テストを実行する可能性は低いからです。
E コマーススキーマ
// Can have 1 customer
// Can have many order details
model CustomerOrder {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
customer Customer @relation(fields: [customerId], references: [id])
customerId Int
orderDetails OrderDetails[]
}
// Can have 1 order
// Can have many products
model OrderDetails {
id Int @id @default(autoincrement())
products Product @relation(fields: [productId], references: [id])
productId Int
order CustomerOrder @relation(fields: [orderId], references: [id])
orderId Int
total Decimal
quantity Int
}
// Can have many order details
// Can have 1 category
model Product {
id Int @id @default(autoincrement())
name String
description String
price Decimal
sku Int
orderDetails OrderDetails[]
category Category @relation(fields: [categoryId], references: [id])
categoryId Int
}
// Can have many products
model Category {
id Int @id @default(autoincrement())
name String
products Product[]
}
// Can have many orders
model Customer {
id Int @id @default(autoincrement())
email String @unique
address String?
name String?
orders CustomerOrder[]
}
このガイドでは、Prisma Client のセットアップにシングルトンパターンを使用しています。セットアップ方法の詳細については、シングルトンドキュメントを参照してください。
Docker をプロジェクトに追加する
Docker と Docker compose の両方がマシンにインストールされている場合、プロジェクトで使用できます。
- まず、プロジェクトのルートに
docker-compose.yml
ファイルを作成します。ここに Postgres イメージを追加し、環境の資格情報を指定します。
# Set the version of docker compose to use
version: '3.9'
# The containers that compose the project
services:
db:
image: postgres:13
restart: always
container_name: integration-tests-prisma
ports:
- '5433:5432'
environment:
POSTGRES_USER: prisma
POSTGRES_PASSWORD: prisma
POSTGRES_DB: tests
注: ここで使用されている compose バージョン (
3.9
) は、執筆時点での最新バージョンです。一貫性を保つために、同じバージョンを使用してください。
docker-compose.yml
ファイルは、以下を定義します
- Postgres イメージ (
postgres
) とバージョンタグ (:13
)。これは、ローカルで利用できない場合にダウンロードされます。 - ポート
5433
は、内部 (Postgres のデフォルト) ポート5432
にマッピングされます。これは、データベースが外部に公開されるポート番号になります。 - データベースのユーザー資格情報が設定され、データベースに名前が付けられます。
- コンテナ内のデータベースに接続するには、
docker-compose.yml
ファイルで定義された資格情報を使用して、新しい接続文字列を作成します。例:
DATABASE_URL="postgresql://prisma:prisma@localhost:5433/tests"
上記の .env.test
ファイルは、複数の .env
ファイルのセットアップの一部として使用されます。複数の .env
ファイルを使用したプロジェクトのセットアップの詳細については、「複数の .env ファイルの使用」セクションを参照してください。
- ターミナルタブを引き続き使用できるように、デタッチされた状態でコンテナを作成するには、次のコマンドを実行します
docker compose up -d
-
次に、コンテナ内で
psql
コマンドを実行して、データベースが作成されたことを確認できます。コンテナ ID をメモしてください。docker ps
表示CLI結果CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1322e42d833f postgres:13 "docker-entrypoint.s…" 2 seconds ago Up 1 second 0.0.0.0:5433->5432/tcp integration-tests-prisma
注: コンテナ ID はコンテナごとに一意であり、異なる ID が表示されます。
-
前の手順のコンテナ ID を使用して、コンテナ内で
psql
を実行し、作成したユーザーでログインして、データベースが作成されていることを確認しますdocker exec -it 1322e42d833f psql -U prisma tests
表示CLI結果tests=# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
postgres | prisma | UTF8 | en_US.utf8 | en_US.utf8 |
template0 | prisma | UTF8 | en_US.utf8 | en_US.utf8 | =c/prisma +
| | | | | prisma=CTc/prisma
template1 | prisma | UTF8 | en_US.utf8 | en_US.utf8 | =c/prisma +
| | | | | prisma=CTc/prisma
tests | prisma | UTF8 | en_US.utf8 | en_US.utf8 |
(4 rows)
統合テスト
統合テストは、本番環境または開発環境ではなく、専用のテスト環境のデータベースに対して実行されます。
操作の流れ
上記のテストを実行する流れは次のとおりです
- コンテナを起動してデータベースを作成する
- スキーマをマイグレートする
- テストを実行する
- コンテナを破棄する
各テストスイートは、すべてのテストが実行される前にデータベースをシードします。スイート内のすべてのテストが終了すると、すべてのテーブルからデータが削除され、接続が終了します。
テストする関数
テストしている e コマースアプリケーションには、注文を作成する関数があります。この関数は次のことを行います
- 注文を行う顧客に関する入力を受け入れる
- 注文される製品に関する入力を受け入れる
- 顧客が既存のアカウントを持っているかどうかを確認する
- 製品が在庫があるかどうかを確認する
- 製品が存在しない場合は、「在庫切れ」メッセージを返す
- 顧客がデータベースに存在しない場合は、アカウントを作成する
- 注文を作成する
そのような関数がどのように見えるかの例を以下に示します
import prisma from '../client'
export interface Customer {
id?: number
name?: string
email: string
address?: string
}
export interface OrderInput {
customer: Customer
productId: number
quantity: number
}
/**
* Creates an order with customer.
* @param input The order parameters
*/
export async function createOrder(input: OrderInput) {
const { productId, quantity, customer } = input
const { name, email, address } = customer
// Get the product
const product = await prisma.product.findUnique({
where: {
id: productId,
},
})
// If the product is null its out of stock, return error.
if (!product) return new Error('Out of stock')
// If the customer is new then create the record, otherwise connect via their unique email
await prisma.customerOrder.create({
data: {
customer: {
connectOrCreate: {
create: {
name,
email,
address,
},
where: {
email,
},
},
},
orderDetails: {
create: {
total: product.price,
quantity,
products: {
connect: {
id: product.id,
},
},
},
},
},
})
}
テストスイート
以下のテストでは、createOrder
関数が意図したとおりに動作するかどうかを確認します。次のことをテストします
- 新規顧客による新規注文の作成
- 既存顧客による注文の作成
- 製品が存在しない場合は、「在庫切れ」エラーメッセージを表示する
テストスイートが実行される前に、データベースにデータがシードされます。テストスイートが終了すると、deleteMany
を使用してデータベースからデータがクリアされます。
deleteMany
の使用は、スキーマの構造を事前に把握している状況では十分な場合があります。これは、モデルリレーションシップの設定方法に従って、操作を正しい順序で実行する必要があるためです。
ただし、これはモデルをマッピングしてそれらを切り捨てる、より一般的なソリューションほどうまくスケールしません。これらのシナリオと生の SQL クエリの使用例については、「生の SQL / TRUNCATE
を使用してすべてのデータを削除する」を参照してください。
import prisma from '../src/client'
import { createOrder, Customer, OrderInput } from '../src/functions/index'
beforeAll(async () => {
// create product categories
await prisma.category.createMany({
data: [{ name: 'Wand' }, { name: 'Broomstick' }],
})
console.log('✨ 2 categories successfully created!')
// create products
await prisma.product.createMany({
data: [
{
name: 'Holly, 11", phoenix feather',
description: 'Harry Potters wand',
price: 100,
sku: 1,
categoryId: 1,
},
{
name: 'Nimbus 2000',
description: 'Harry Potters broom',
price: 500,
sku: 2,
categoryId: 2,
},
],
})
console.log('✨ 2 products successfully created!')
// create the customer
await prisma.customer.create({
data: {
name: 'Harry Potter',
email: 'harry@hogwarts.io',
address: '4 Privet Drive',
},
})
console.log('✨ 1 customer successfully created!')
})
afterAll(async () => {
const deleteOrderDetails = prisma.orderDetails.deleteMany()
const deleteProduct = prisma.product.deleteMany()
const deleteCategory = prisma.category.deleteMany()
const deleteCustomerOrder = prisma.customerOrder.deleteMany()
const deleteCustomer = prisma.customer.deleteMany()
await prisma.$transaction([
deleteOrderDetails,
deleteProduct,
deleteCategory,
deleteCustomerOrder,
deleteCustomer,
])
await prisma.$disconnect()
})
it('should create 1 new customer with 1 order', async () => {
// The new customers details
const customer: Customer = {
id: 2,
name: 'Hermione Granger',
email: 'hermione@hogwarts.io',
address: '2 Hampstead Heath',
}
// The new orders details
const order: OrderInput = {
customer,
productId: 1,
quantity: 1,
}
// Create the order and customer
await createOrder(order)
// Check if the new customer was created by filtering on unique email field
const newCustomer = await prisma.customer.findUnique({
where: {
email: customer.email,
},
})
// Check if the new order was created by filtering on unique email field of the customer
const newOrder = await prisma.customerOrder.findFirst({
where: {
customer: {
email: customer.email,
},
},
})
// Expect the new customer to have been created and match the input
expect(newCustomer).toEqual(customer)
// Expect the new order to have been created and contain the new customer
expect(newOrder).toHaveProperty('customerId', 2)
})
it('should create 1 order with an existing customer', async () => {
// The existing customers email
const customer: Customer = {
email: 'harry@hogwarts.io',
}
// The new orders details
const order: OrderInput = {
customer,
productId: 1,
quantity: 1,
}
// Create the order and connect the existing customer
await createOrder(order)
// Check if the new order was created by filtering on unique email field of the customer
const newOrder = await prisma.customerOrder.findFirst({
where: {
customer: {
email: customer.email,
},
},
})
// Expect the new order to have been created and contain the existing customer with an id of 1 (Harry Potter from the seed script)
expect(newOrder).toHaveProperty('customerId', 1)
})
it("should show 'Out of stock' message if productId doesn't exit", async () => {
// The existing customers email
const customer: Customer = {
email: 'harry@hogwarts.io',
}
// The new orders details
const order: OrderInput = {
customer,
productId: 3,
quantity: 1,
}
// The productId supplied doesn't exit so the function should return an "Out of stock" message
await expect(createOrder(order)).resolves.toEqual(new Error('Out of stock'))
})
テストの実行
このセットアップは、制御された環境で実際のデータに対してアプリケーションの機能をテストできるように、現実世界のシナリオを分離します。
データベースをセットアップしてテストを実行し、その後コンテナを手動で破棄するスクリプトをプロジェクトの package.json
ファイルに追加できます。
テストが機能しない場合は、このブログで説明されているように、テストデータベースが適切にセットアップされ、準備ができていることを確認する必要があります。
"scripts": {
"docker:up": "docker compose up -d",
"docker:down": "docker compose down",
"test": "yarn docker:up && yarn prisma migrate deploy && jest -i"
},
test
スクリプトは次のことを行います
docker compose up -d
を実行して、Postgres イメージとデータベースを含むコンテナを作成します。./prisma/migrations/
ディレクトリにあるマイグレーションをデータベースに適用します。これにより、コンテナのデータベースにテーブルが作成されます。- テストを実行します。
満足したら、yarn docker:down
を実行して、コンテナ、そのデータベース、およびテストデータを破棄できます。