constructive-test
v2.11.5
Published
Constructive GraphQL Testing with all plugins loaded
Maintainers
Readme
@constructive-io/graphql-test
@constructive-io/graphql-test builds on top of pgsql-test to provide robust GraphQL testing utilities for PostGraphile-based projects with all Constructive plugins pre-configured.
It provides a seamless setup for isolated, seeded, role-aware Postgres databases and injects GraphQL helpers for snapshot testing, role context, and mutation/query assertions. This package includes all the default plugins from graphile-settings (connection filters, full-text search, PostGIS, uploads, i18n, etc.) for a batteries-included testing experience.
🚀 Features
- 🔁 Per-test rollback via savepoints for isolation
- 🔐 RLS-aware context injection (
setContext) - 🧪 GraphQL integration testing with
query()and snapshot support - 📦 Seed support for
.sql, JSON, CSV, Constructive, or Sqitch - 📊 Introspection query snapshotting
- 🔧 Raw SQL fallback via
pg.client.query
📦 Install
npm install @constructive-io/graphql-test✨ Quick Start
import { getConnections, seed } from '@constructive-io/graphql-test';
let db, query, teardown;
beforeAll(async () => {
({ db, query, teardown } = await getConnections({
schemas: ['app_public'],
authRole: 'authenticated'
}, [
seed.sqlfile(['../sql/test.sql', '../sql/grants.sql'])
]));
});
beforeEach(() => db.beforeEach());
afterEach(() => db.afterEach());
afterAll(() => teardown());
it('runs a GraphQL mutation', async () => {
const res = await query(`mutation { ... }`, { input: { ... } });
expect(res.data.createUser.username).toBe('alice');
});📘 API
getConnections(options, seeders)
Returns an object with:
query(gqlString, variables?)– A GraphQL executor function with positional argumentsdb,pg–PgTestClientinstancesteardown()– Clean up temp DBs
Basic Usage:
const result = await query(`mutation { ... }`, { input: { ... } });
expect(result.data.createUser.username).toBe('alice');PgTestClient
Supports:
query,any,one, etc. (viapg-promise-like helpers)beforeEach()/afterEach()– for savepoint transaction handlingsetContext({...})– sets Postgres config (e.g.,role,myapp.user_id)
See full PgTestClient API docs: pgsql-test → PgTestClient API Overview
🧪 Example Tests
GraphQL mutation + snapshot
const res = await query(`mutation { ... }`, { input: { ... } });
expect(snapshot(res.data)).toMatchSnapshot();RLS testing with role switch
db.setContext({ role: 'anonymous' });
const res = await query(`query { ... }`);
expect(res.errors[0].message).toMatch(/permission denied/);Typed queries for better safety
interface CreateUserVariables {
input: {
user: {
username: string;
};
};
}
interface CreateUserResult {
createUser: {
user: {
id: number;
username: string;
};
};
}
const res = await query<CreateUserResult, CreateUserVariables>(`
mutation CreateUser($input: CreateUserInput!) {
createUser(input: $input) {
user {
id
username
}
}
}
`,
{ input: { user: { username: 'alice' } } }
);
expect(res.data?.createUser.user.username).toBe('alice');🔧 Advanced Connection Options
For specific testing needs, additional connection functions are available:
Error Handling Variants
getConnectionsUnwrapped()– Automatically throws on GraphQL errors, returns data directly
Debugging Variants
getConnectionsWithLogging()– Logs all queries and responsesgetConnectionsWithTiming()– Times query execution
Object-Based API
getConnectionsObject()– Usesquery({ query: "...", variables: {} })syntaxgetConnectionsObjectUnwrapped()– Object-based with automatic error throwing
Unwrapped Example (cleaner assertions):
import { getConnectionsUnwrapped } from 'graphile-test';
const { query } = await getConnectionsUnwrapped(config);
// Throws automatically on GraphQL errors, returns data directly
const result = await query(`mutation { ... }`, { input: { ... } });
expect(result.createUser.username).toBe('alice'); // No .data needed!Object-Based Example:
import { getConnectionsObject } from 'graphile-test';
const { query } = await getConnectionsObject(config);
const result = await query({
query: `mutation { ... }`,
variables: { input: { ... } }
});
expect(result.data.createUser.username).toBe('alice');🧱 Under the Hood
graphile-test wraps and extends pgsql-test with GraphQL helpers like query() and introspection snapshot tools. You can drop into raw SQL testing anytime via pg.client.query() (superuser) or db.client.query() (RLS user).
✅ Best Practices
- Use
db.setContext({ role, user_id })to simulate authentication. - Always wrap tests with
beforeEach/afterEach. - Use
snapshot()to track GraphQL result changes. - Use
useRoot: trueto test schema visibility without RLS. - Start with
getConnections()for most use cases. - Consider
getConnectionsUnwrapped()for cleaner test assertions.
Snapshot Utilities
The @constructive-io/graphql-test/utils module provides utilities for sanitizing query results for snapshot testing. These helpers replace dynamic values (IDs, UUIDs, dates, hashes) with stable placeholders, making snapshots deterministic.
import { snapshot } from '@constructive-io/graphql-test/utils';
const res = await query(`query { allUsers { nodes { id name createdAt } } }`);
expect(snapshot(res.data)).toMatchSnapshot();See pgsql-test Snapshot Utilities for the full API reference.
Education and Tutorials
🚀 Quickstart: Getting Up and Running Get started with modular databases in minutes. Install prerequisites and deploy your first module.
📦 Modular PostgreSQL Development with Database Packages Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
✏️ Authoring Database Changes Master the workflow for adding, organizing, and managing database changes with pgpm.
🧪 End-to-End PostgreSQL Testing with TypeScript Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
⚡ Supabase Testing Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
💧 Drizzle ORM Testing Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
🔧 Troubleshooting Common issues and solutions for pgpm, PostgreSQL, and testing.
Related Constructive Tooling
🧪 Testing
- pgsql-test: 📊 Isolated testing environments with per-test transaction rollbacks—ideal for integration tests, complex migrations, and RLS simulation.
- supabase-test: 🧪 Supabase-native test harness preconfigured for the local Supabase stack—per-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
- graphile-test: 🔐 Authentication mocking for Graphile-focused test helpers and emulating row-level security contexts.
- pg-query-context: 🔒 Session context injection to add session-local context (e.g.,
SET LOCAL) into queries—ideal for settingrole,jwt.claims, and other session settings.
🧠 Parsing & AST
- pgsql-parser: 🔄 SQL conversion engine that interprets and converts PostgreSQL syntax.
- libpg-query-node: 🌉 Node.js bindings for
libpg_query, converting SQL into parse trees. - pg-proto-parser: 📦 Protobuf parser for parsing PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
- @pgsql/enums: 🏷️ TypeScript enums for PostgreSQL AST for safe and ergonomic parsing logic.
- @pgsql/types: 📝 Type definitions for PostgreSQL AST nodes in TypeScript.
- @pgsql/utils: 🛠️ AST utilities for constructing and transforming PostgreSQL syntax trees.
- pg-ast: 🔍 Low-level AST tools and transformations for Postgres query structures.
🚀 API & Dev Tools
- @constructive-io/graphql-server: ⚡ Express-based API server powered by PostGraphile to expose a secure, scalable GraphQL API over your Postgres database.
- @constructive-io/graphql-explorer: 🔎 Visual API explorer with GraphiQL for browsing across all databases and schemas—useful for debugging, documentation, and API prototyping.
🔁 Streaming & Uploads
- etag-hash: 🏷️ S3-compatible ETags created by streaming and hashing file uploads in chunks.
- etag-stream: 🔄 ETag computation via Node stream transformer during upload or transfer.
- uuid-hash: 🆔 Deterministic UUIDs generated from hashed content, great for deduplication and asset referencing.
- uuid-stream: 🌊 Streaming UUID generation based on piped file content—ideal for upload pipelines.
- @constructive-io/s3-streamer: 📤 Direct S3 streaming for large files with support for metadata injection and content validation.
- @constructive-io/upload-names: 📂 Collision-resistant filenames utility for structured and unique file names for uploads.
🧰 CLI & Codegen
- pgpm: 🖥️ PostgreSQL Package Manager for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
- @constructive-io/cli: 🖥️ Command-line toolkit for managing Constructive projects—supports database scaffolding, migrations, seeding, code generation, and automation.
- @constructive-io/graphql-codegen: ✨ GraphQL code generation (types, operations, SDK) from schema/endpoint introspection.
- @constructive-io/query-builder: 🏗️ SQL constructor providing a robust TypeScript-based query builder for dynamic generation of
SELECT,INSERT,UPDATE,DELETE, and stored procedure calls—supports advanced SQL features likeJOIN,GROUP BY, and schema-qualified queries. - @constructive-io/graphql-query: 🧩 Fluent GraphQL builder for PostGraphile schemas. ⚡ Schema-aware via introspection, 🧩 composable and ergonomic for building deeply nested queries.
Credits
🛠 Built by the Constructive team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on GitHub.
Disclaimer
AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
