test: npm test starts a throwaway Postgres when TEST_DATABASE_URL is unset

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfmHGGiYUjNcvJoyzdf
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-12-01 11:56:11 +08:00
1 parent f78bd635a2
commit 20e07e9d80
4 files changed
+19 -3

No files matched your search

+1 -1
View File
@@ -16,7 +16,7 @@ docker run -d --name ins-pg -e POSTGRES_USER=ins -e POSTGRES_DB=ins -e POSTGRES_
-p 127.0.0.1:5432:5432 postgres:18
npm ci
DATABASE_URL=postgres://ins:devpass@127.0.0.1:5432/ins npm start # http://localhost:3000
TEST_DATABASE_URL=postgres://ins:devpass@127.0.0.1:5432/ins npm test
npm test # starts a throwaway Postgres in Docker, or uses TEST_DATABASE_URL if set
```
Environment: `DATABASE_URL` (required), `PORT` (default `3000`). Tests create their own schema in `TEST_DATABASE_URL` and drop it afterwards; they never touch an existing `leads` table.
+1 -1
View File
@@ -6,7 +6,7 @@
},
"scripts": {
"start": "node server.js",
"test": "node --test"
"test": "scripts/test.sh"
},
"dependencies": {
"pg": "8.23.1"
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env bash
# npm test: use TEST_DATABASE_URL if set (CI does), otherwise start a throwaway Postgres in Docker,
# run the tests against it, and remove it again.
set -euo pipefail
cd "$(dirname "$0")/.."
if [ -n "${TEST_DATABASE_URL:-}" ]; then exec node --test "$@"; fi
name="ins-test-pg-$$"
pw="$(od -An -N16 -tx1 /dev/urandom | tr -d ' \n')"
trap 'docker rm -f "$name" >/dev/null 2>&1 || true' EXIT
docker run -d --name "$name" -e POSTGRES_USER=test -e POSTGRES_DB=test -e POSTGRES_PASSWORD="$pw" \
-p 127.0.0.1::5432 postgres:18 >/dev/null
# -h 127.0.0.1: the image first starts a socket-only init server; TCP answers only once it is really up
for _ in $(seq 1 30); do docker exec "$name" pg_isready -h 127.0.0.1 -U test -d test >/dev/null 2>&1 && break; sleep 1; done
port="$(docker port "$name" 5432/tcp | head -1 | sed 's/.*://')"
TEST_DATABASE_URL="postgres://test:$pw@127.0.0.1:$port/test" node --test "$@"
+1 -1
View File
@@ -1,4 +1,4 @@
// Needs a Postgres to test against: TEST_DATABASE_URL=postgres://user:pass@host:port/db npm test
// Run with `npm test` (starts a throwaway Postgres), or set TEST_DATABASE_URL=postgres://user:pass@host:port/db
// Each run creates its own schema and drops it afterwards, so existing tables are never touched.
const { test, before, after } = require('node:test');
const assert = require('node:assert');