🐘 instantly stand up full Postgres databases in your AVA tests

Overview

ava-postgres

ava-postgres is a test fixture for AVA that provides you with nearly-instant access to a fresh Postgres database for every test.

Installation

npm install --save-dev ava-postgres

or

yarn add --dev ava-postgres

Usage

ava-postgres's main export is a factory function, so you'll probably want to create a file like tests/fixtures/get-test-database.ts:

import { getTestPostgresDatabaseFactory } from "ava-postgres"

export const getTestDatabase = getTestPostgresDatabaseFactory({
  // Any tag for the official Postgres Docker image, defaults to "14"
  postgresVersion: "14",
})

Then, in your tests, you can use the getTestDatabase() function to get a fresh database for each test:

import test from "ava"
import { getTestDatabase } from "./fixtures/get-test-database"

test("foo bar", async (t) => {
  const { pool } = await getTestDatabase()

  await pool.query("SELECT 1")

  t.pass()
})

Database setup

ava-postgres uses Postgres templates so you only pay the setup cost once. After a template has been created, Postgres can create a new database from it in milliseconds.

If you want to perform common database setup, you can use a hook and pass parameters to the getTestDatabase() function:

import { getTestPostgresDatabaseFactory } from "ava-postgres"

type GetTestDatabaseParams = {
  shouldMigrate?: boolean
  shouldSeed?: boolean
}

export const getTestDatabase =
  getTestPostgresDatabaseFactory<GetTestDatabaseParams>({
    beforeTemplateIsBaked: async ({
      connection: { pool },
      params: { shouldMigrate, shouldSeed },
    }) => {
      if (shouldMigrate) {
        await pool.query("CREATE TABLE foo (id int)")
      }

      if (shouldSeed) {
        await pool.query("INSERT INTO foo VALUES (1)")
      }
    },
  })

Then, in your tests, you can pass parameters to the getTestDatabase() function:

import test from "ava"
import { getTestDatabase } from "./fixtures/get-test-database"

test("foo bar", async (t) => {
  const { pool } = await getTestDatabase({
    shouldMigrate: true,
    shouldSeed: true,
  })

  await pool.query("SELECT * FROM foo")

  t.pass()
})

Advanced Usage

Bind mounts & execing in the container

ava-postgres uses testcontainers under the hood to manage the Postgres container.

In some scenarios you might want to mount a SQL script into the container and manually load it using psql.

You can do this with the bindMounts option:

const getTestPostgresDatabase = getTestPostgresDatabaseFactory({
  container: {
    bindMounts: [
      {
        source: "/path/on/host",
        target: "/test.sql",
      },
    ],
  },
  beforeTemplateIsBaked: async ({
    connection: { username, database },
    containerExec,
  }) => {
    const { exitCode } = await containerExec(
      `psql -U ${username} -d ${database} -f /test.sql`.split(" ")
    )

    if (exitCode !== 0) {
      throw new Error(`Failed to load test file`)
    }
  },
})
You might also like...

A multipurpose transporting app that contains, loads databases, documentation and more.

TransportingApp This project was generated with Angular CLI version 12.0.3. Development server Run ng serve for a dev server. Navigate to http://local

Jan 21, 2022

Enables creating databases based on files in Obsidian - like Dataview, but with editing!

Enables creating databases based on files in Obsidian - like Dataview, but with editing!

Obsidian Database Plugin Do you like Dataview plugin for Obsidian? This one is taking Dataview to next level, but not only allowing you to view the da

Jan 4, 2023

E-Commerce solution for security of databases and transactions.

commerce_new_era AMAΓ‡ AmacΔ±mΔ±z gΓΌnΓΌmΓΌzde E-Ticaret sitelerinde bulunan sahte ΓΌrΓΌnlerin ve mağduriyetlerin ΓΆnΓΌne geΓ§mektir. Bunu yapmak iΓ§in Blockchai

May 14, 2022

πŸ‰ Water is a micro-ORM + QueryBuilder designed to facilitate queries and operations on PostgreSQL databases designed to work in Melon

πŸ‰ Water Water is a micro-ORM + QueryBuilder designed to facilitate queries and operations on PostgreSQL databases designed to work in MelonRuntime In

Aug 6, 2022

CDK construct to periodically take snapshots of RDS databases, sanitize them, and share with selected accounts.

CDK Construct for RDS Sanitized Snapshots Periodically take snapshots of RDS databases, sanitize them, and share with selected accounts. Use this to a

Dec 7, 2022

IPLD transaction as CAR buffer [for use in databases]

car-transaction IPLD transaction as CAR buffer that can be used as a database transaction. Usage import Transaction from 'car-transaction' const run

Sep 17, 2022

Preserve `localStorage` in databases.

PLS Preserve localStorage in databases. Features No adapter dependency is loaded by default. Possible to write/contribute your own adapters. Currently

Nov 3, 2022

Apply version control to databases from within a Node.js application.

Node Flyway Apply version control to databases from within a Node.js application. Uses Flyway for database version control, schema evolution and migra

Sep 6, 2022

Use better-sqlite3 to give obsidian the ability to manipulate sqlite3 databases

OBSIDIAN-SQLITE3 Use better-sqlite3 to give obisidian the ability to manipulate sqlite3 databases. Intention Currently the linkage between obsidian an

Nov 28, 2022
Comments
  • BREAKING CHANGE: Update testcontainers to version 9

    BREAKING CHANGE: Update testcontainers to version 9

    See https://github.com/testcontainers/testcontainers-node/releases/tag/v9.0.0

    Replace networkNameDocker with networkName:

    • The ConnectionDetails type now includes the Network as networkDocker.
    • The networkNameDocker property has been removed.
    opened by razor-x 1
Owner
Seam
The API for the Physical World
Seam
RepoProvas API, a system for sharing tests between students, built with Typescript, Node.js, Express, Prisma and Postgres.

Repoprovas Built With ?? Description RepoProvas API, a system for sharing tests between students, built with Typescript, Node.js, Express, Prisma and

Lucas Lima 3 Dec 13, 2022
Host your own replica server instantly on Glitch.

Earthstar Replica Server for Glitch Want your own replica server? Click the button above. Create a file at .data/known_shares.json Add the shares you'

Earthstar Project 5 Apr 26, 2022
SAP Community Code Challenge: This repository contains an empty OpenUI5 application and end-to-end tests written with wdi5. Take part in the challenge and develop an app that passes the tests.

SAP Community Code Challenge - UI5 The change log describes notable changes in this package. Description This repository is the starting point for the

SAP Samples 8 Oct 24, 2022
A bot that instantly translates messages on Discord.

Translate Thing A bot that instantly translates messages on Discord. Here is a lil preview. Setup All you need to do is install NodeJS if you do not h

Amelia 2 Oct 23, 2022
πŸ–ŠοΈOpen a VSCode temporary file instantly

vscode-tempfile This extension immediately creates a temporary file and opens it in a new tab. Configuration You can specify the new file path and ini

Tetsu 1 Oct 5, 2022
Postgres.js - The Fastest full featured PostgreSQL client for Node.js and Deno

?? Fastest full-featured node & deno client ?? ES6 Tagged Template Strings at the core ??‍♀️ Simple surface API ??️ Dynamic query support ?? Chat and

Rasmus Porsager 4.3k Jan 1, 2023
Example-browserstack-reporting - This repository contains an example of running Selenium tests and reporting BrowserStack test results, including full CI pipeline integration.

BrowserStack reporting and Selenium test result example This repository contains an example of running Selenium tests and reporting BrowserStack test

Testmo 1 Jan 1, 2022
Fastest way to get financial data from Plaid into your Postgres database. Go from zero to live in 5 minutes without a single line of code.

Venice Venice is a the fastest way to get financial data from Plaid into your Postgres database. Zero to production in 5 minutes without a single line

Venice 93 Dec 12, 2022
Cooperative databases using smart contracts.

Vitra β–ˆβ–ˆβ•— β–ˆβ–ˆβ•—β–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β•šβ•β•β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘ β•šβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆ

Paul Frazee 177 Dec 30, 2022