Skip to content
当前有符合你浏览器所设置语言的版本,是否前往zh-CN版本的网站?
There is a version suitable for your browser's language settings. Would you like to go to the zh-CN language of the site?
HomeDocument

Test

H1

To ensure that tests are free of side effects and independent, we can empty the database before each test.

Example

Edit the /src/api-test.ts file. The onBefore method will be executed before each test run.

In this method, we can empty the database before each test starts.

/src/api-test.ts
import { $ } from "bun";
import { sql } from "drizzle-orm";
import { useDrizzle } from "./uses/drizzle";
import { configDrizzle } from "./config/drizzle";
export default {
async onBootstrap() {},
async onBefore() {
const drizzle = await useDrizzle();
const schema = await import("../generated/database-schema");
// Find all tables
const tables: Array<string> = [];
for (const key in schema) "getSQL" in schema[key] && tables.push(getTableName(schema[key] as unknown as Table));
// Drop all these tables
for (const table of tables) await drizzle.execute(sql.raw(`DROP TABLE IF EXISTS ${table};`));
// Re-create these tables using drizzle-kit
await $`bun x drizzle-kit push`;
return {};
},
};