ARTICLE AD BOX
I'm using vitest to run my e2e tests. I plan to create a different PostgreSQL schema to run tests. To set up this schema automatically, I've done this (following vitest's docs):
// vitest-environment-prisma.ts
import { execSync } from 'node:child_process' import { randomUUID } from 'node:crypto' import type { Environment } from 'vitest/environments' import 'dotenv/config' function makeDatabaseUrl(schema: string) { const connectionString = process.env.DATABASE_URL if (!connectionString) { throw new Error('DATABASE_URL environment variable missing.') } const databaseUrl = new URL(connectionString) databaseUrl.searchParams.set('schema', schema) return databaseUrl.toString() } export default <Environment> { name: 'prisma', viteEnvironment: 'ssr', setup: async function () { const schema = randomUUID() process.env.DATABASE_URL = makeDatabaseUrl(schema) execSync('npx prisma migrate deploy') return { teardown: async function () { }, } }, }Now, I try to run my only e2e test so far:
import { app } from '@/app.js' import { prisma } from '@/lib/prisma.js' import { afterAll, beforeAll, describe, expect, it } from 'vitest' describe('Register User (e2e)', () => { beforeAll(async () => { await app.ready() }) afterAll(async () => { await app.close() }) it('Should register user', async () => { const a = await prisma.$queryRaw`SELECT current_schema();` console.log(a) const user = { name: 'John Doe', email: '[email protected]', password: '12435djdj!', } const response = await app.inject({ method: 'POST', path: '/users', body: user, }) expect(response.statusCode).toEqual(201) }) })I've been getting an error saying that the user already exists. It's my app's behavior to do this. But, since I was (or should be) using a clean db schema, it should not have anything in it. So I added that "a" console.log and this is what I get: [ { current_schema: 'public' } ]
So prisma still uses the default schema, even though I changed process.env.DATABASE_URL to use a brand new schema.
What am I doing wrong? Edit: this is my lib/prisma.ts file: (I don't know how to format)
import { env } from '@/env/index.js' import { PrismaClient } from '../../prisma/generated/prisma/client.js' import { PrismaPg } from '@prisma/adapter-pg' export const prisma = new PrismaClient({ adapter: new PrismaPg({ connectionString: env.DATABASE_URL, }), log: env.NODE_ENV === 'development' ? ['query'] : [], })