npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

constructive-test

v2.11.5

Published

Constructive GraphQL Testing with all plugins loaded

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 arguments
  • db, pgPgTestClient instances
  • teardown() – 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. (via pg-promise-like helpers)
  • beforeEach() / afterEach() – for savepoint transaction handling
  • setContext({...}) – 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 responses
  • getConnectionsWithTiming() – Times query execution

Object-Based API

  • getConnectionsObject() – Uses query({ query: "...", variables: {} }) syntax
  • getConnectionsObjectUnwrapped() – 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: true to 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

  1. 🚀 Quickstart: Getting Up and Running Get started with modular databases in minutes. Install prerequisites and deploy your first module.

  2. 📦 Modular PostgreSQL Development with Database Packages Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.

  3. ✏️ Authoring Database Changes Master the workflow for adding, organizing, and managing database changes with pgpm.

  4. 🧪 End-to-End PostgreSQL Testing with TypeScript Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.

  5. Supabase Testing Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.

  6. 💧 Drizzle ORM Testing Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.

  7. 🔧 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 setting role, 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 like JOIN, 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.