When setting up your database, you have to make sure your environment is setup before you run the test. To do that, you can use globalSetup. You then, have to import it to your setupFile on top of the file, because it must run before anything else.

Database Setup for test

To setup database for your test, you have to do the following:

  • Create a base of a database with required seeds etc. so you can copy it for every test instead of creating a new one and doing it every time you run a test
  • Make sure you override the database URL variable (or any other variable that is needed for your ORM)
  • Reset database before all tests start to avoid situations where during seeding process, test errors, because the entity in a database already exists
  • After each test, you delete everything from the database to clean up after yourself
  • Disconnect from the database once you finish running the test.

setupFiles

import path from 'node:path'  
import { execaCommand } from 'execa'  
import { afterAll, beforeAll, beforeEach } from 'vitest'  
import {BASE_DATABASE_PATH} from "globalSetupFile"  
  
const databaseFile = `./tests/prisma/data.${VITEST_POOOL_ID || 0}.db`  
const databasePath = path.join(process.cwd(), databaseFile)  
process.env.DATABASE_URL = databasePath  
  
beforeAll(async () => {  
	await fsExtra.copyFile(BASE_DATABASE_PATH, databaseFile)  
})  
  
beforeEach(async () => {  
	const { prisma } = await import('#app/utils/db.server.ts')  
	await prisma.user.deleteMany()  
})  
  
afterAll(async () => {  
	const { prisma } = await import('#app/utils/db.server.ts')  
	await prisma.$disconnect()  
})  

globalSetup

import path from 'node:path'  
import { execaCommand } from 'execa'  
import fsExtra from 'fs-extra'  
  
export const BASE_DATABASE_PATH = path.join(  
	process.cwd(),  
	'./tests/prisma/base.db',  
)  
  
export async function setup() {  
	const exists = await fsExtra.pathExists(BASE_DATABASE_PATH)  
	if (exists) return  
  
	await execaCommand(  
		'prisma migrate reset --force --skip-seed --skip-generate',  
		{  
			stdio: 'inherit',  
			env: { ...process.env, DATABASE_URL: `file:${BASE_DATABASE_PATH}` },  
		},  
	)  
}