整合測試
整合測試側重於測試程式中各個獨立部分如何協同工作。在使用資料庫的應用程式上下文中,整合測試通常需要一個可用的資料庫,並且包含適合待測試場景的資料。
一種模擬真實世界環境的方法是使用 Docker 來封裝資料庫和一些測試資料。這可以在測試中啟動和關閉,從而作為與生產資料庫隔離的環境執行。
注意: 這篇 部落格文章 提供了一個關於設定整合測試環境以及針對真實資料庫編寫整合測試的全面指南,為那些希望深入瞭解此主題的人提供了寶貴的見解。
先決條件
本指南假設你的機器上已安裝 Docker 和 Docker Compose,並且在你的專案中設定了 Jest。
本指南將全程使用以下電商 schema。這與文件其他部分使用的傳統 User 和 Post 模型不同,主要是因為你不太可能對你的部落格執行整合測試。
電商 schema
// 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)
整合測試
整合測試將針對專用測試環境中的資料庫執行,而不是針對生產或開發環境。
操作流程
執行此類測試的流程如下:
- 啟動容器並建立資料庫
- 遷移 schema
- 執行測試
- 銷燬容器
每個測試套件都會在所有測試執行之前為資料庫播種資料。在套件中的所有測試完成後,將清除所有表中的資料並終止連線。
待測試函式
你正在測試的電商應用有一個建立訂單的函式。此函式執行以下操作:
- 接受有關下訂單客戶的輸入
- 接受有關所訂購產品的輸入
- 檢查客戶是否已有賬戶
- 檢查產品是否有庫存
- 如果產品不存在,則返回“缺貨”訊息
- 如果客戶在資料庫中不存在,則建立賬戶
- 建立訂單
此類函式可能的樣子可以在下面看到:
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 清除資料庫中的資料。
在你知道 schema 結構的情況下,使用 deleteMany 可能就足夠了。這是因為操作需要根據模型關係設定以正確的順序執行。
然而,這不如一個更通用的解決方案可擴充套件,後者可以遍歷你的模型並對其執行截斷(truncate)操作。有關這些場景以及使用原始 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 來銷燬容器、其資料庫和任何測試資料。