Skip to content

Instantly share code, notes, and snippets.

@ismael3s
Created June 2, 2022 04:29
Show Gist options
  • Save ismael3s/0c7ac3415934d003031f8fd1c4833ef7 to your computer and use it in GitHub Desktop.
Save ismael3s/0c7ac3415934d003031f8fd1c4833ef7 to your computer and use it in GitHub Desktop.
Setup Prisma Test Envrioment
import { join } from 'path';
import { jest } from './package.json';
export default {
...jest,
preset: "ts-jest",
"testRegex": ".*\\.controller.spec\\.ts$",
"testEnvironment": join(__dirname, "./prisma/test-prisma.js")
};
{
"scripts": {
"test:integration": "jest --config ./jest-integration-config.ts"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.service.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
/* eslint-disable @typescript-eslint/no-var-requires */
const { Client } = require("pg");
const NodeEnvironment = require("jest-environment-node");
const util = require("util");
const { randomUUID } = require("crypto");
const { join } = require("path");
const exec = util.promisify(require("child_process").exec);
const prismaBinary = join(".", "node_modules", ".bin", "prisma2");
class PrismaTestEnvironment extends NodeEnvironment {
constructor(config) {
super(config);
// Generate a unique schema identifier for this test context
this.schema = `test_${randomUUID()}`;
// Generate the pg connection string for the test schema
this.connectionString = `postgresql://postgres:postgres@localhost:5432/tests?schema=${this.schema}`;
}
async setup() {
// Set the required environment variable to contain the connection string
// to our database test schema
process.env.DATABASE_URL = this.connectionString;
this.global.process.env.DATABASE_URL = this.connectionString;
// Run the migrations to ensure our schema has the required structure
await exec(`${prismaBinary} migrate deploy`);
return super.setup();
}
async teardown() {
// Drop the schema after the tests have completed
const client = new Client({
connectionString: this.connectionString,
});
await client.connect();
await client.query(`DROP SCHEMA IF EXISTS "${this.schema}" CASCADE`);
await client.end();
}
}
module.exports = PrismaTestEnvironment;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment