Skip to content

Instantly share code, notes, and snippets.

@Weakky
Created January 15, 2020 21:53
Show Gist options
  • Save Weakky/742ec80338f7fe997ecca4eaf45fa59b to your computer and use it in GitHub Desktop.
Save Weakky/742ec80338f7fe997ecca4eaf45fa59b to your computer and use it in GitHub Desktop.
Jest environment for GraphQL Santa, Prisma & Postgres
const { Client } = require('pg')
const NodeEnvironment = require('jest-environment-node')
const nanoid = require('nanoid')
const util = require('util')
const exec = util.promisify(require('child_process').exec)
const santaBinary = './node_modules/.bin/graphql-santa'
/**
* Custom test environment for graphql-santa and Postgres
*/
class PrismaTestEnvironment extends NodeEnvironment {
constructor(config) {
super(config)
// Generate a unique schema identifier for this test context
this.schema = `test_${nanoid()}`
// Generate the pg connection string for the test schema
this.connectionString = `postgres://postgres:postgres@localhost:5432/testing?schema=${this.schema}`
}
async setup() {
// Set the required environment variable to contain the connection string
// to our database test schema
process.env.POSTGRES_URL = this.connectionString
this.global.process.env.POSTGRES_URL = this.connectionString
// Run the migrations to ensure our schema has the required structure
await exec(`${santaBinary} db migrate apply -f`)
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