@constructive-io/graphql-server-test 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,23 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Dan Lynch <pyramation@gmail.com>
4
+ Copyright (c) 2025 Constructive <developers@constructive.io>
5
+ Copyright (c) 2020-present, Interweb, Inc.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,238 @@
1
+ # @constructive-io/graphql-server-test
2
+
3
+ <p align="center" width="100%">
4
+ <img height="250" src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" />
5
+ </p>
6
+
7
+ <p align="center" width="100%">
8
+ <a href="https://github.com/constructive-io/constructive/actions/workflows/run-tests.yaml">
9
+ <img height="20" src="https://github.com/constructive-io/constructive/actions/workflows/run-tests.yaml/badge.svg" />
10
+ </a>
11
+ <a href="https://github.com/constructive-io/constructive/blob/main/LICENSE">
12
+ <img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/>
13
+ </a>
14
+ <a href="https://www.npmjs.com/package/@constructive-io/graphql-server-test">
15
+ <img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/constructive?filename=graphql%2Fserver-test%2Fpackage.json"/>
16
+ </a>
17
+ </p>
18
+
19
+ `@constructive-io/graphql-server-test` provides a testing framework that spins up a real HTTP server using `@constructive-io/graphql-server` and tests it using SuperTest. Unlike `@constructive-io/graphql-test` which uses direct PostGraphile execution, this package makes actual HTTP requests to test the full middleware stack.
20
+
21
+ ## Install
22
+
23
+ ```sh
24
+ npm install @constructive-io/graphql-server-test
25
+ ```
26
+
27
+ ## Features
28
+
29
+ - Real HTTP server testing with SuperTest
30
+ - Uses `@constructive-io/graphql-server` directly for the full middleware stack
31
+ - Per-test database isolation with transaction rollback
32
+ - Built on top of `pgsql-test` for database management
33
+ - Compatible with Jest and other test runners
34
+
35
+ ## Usage
36
+
37
+ ### Basic Usage
38
+
39
+ ```typescript
40
+ import { getConnections, seed } from '@constructive-io/graphql-server-test';
41
+
42
+ let db, pg, server, query, request, teardown;
43
+
44
+ beforeAll(async () => {
45
+ ({ db, pg, server, query, request, teardown } = await getConnections({
46
+ schemas: ['app_public'],
47
+ authRole: 'anonymous'
48
+ }, [
49
+ seed.sqlfile(['./sql/test.sql'])
50
+ ]));
51
+ });
52
+
53
+ beforeEach(() => db.beforeEach());
54
+ afterEach(() => db.afterEach());
55
+ afterAll(() => teardown());
56
+
57
+ it('queries users via HTTP', async () => {
58
+ const res = await query(`
59
+ query {
60
+ allUsers {
61
+ nodes { id username }
62
+ }
63
+ }
64
+ `);
65
+
66
+ expect(res.data.allUsers.nodes).toHaveLength(2);
67
+ });
68
+ ```
69
+
70
+ ### Using SuperTest Directly
71
+
72
+ For more control over HTTP requests, use the `request` agent directly:
73
+
74
+ ```typescript
75
+ it('tests authentication headers', async () => {
76
+ const res = await request
77
+ .post('/graphql')
78
+ .set('Authorization', 'Bearer test-token')
79
+ .set('Content-Type', 'application/json')
80
+ .send({ query: '{ currentUser { id } }' });
81
+
82
+ expect(res.status).toBe(200);
83
+ expect(res.body.data.currentUser).toBeDefined();
84
+ });
85
+
86
+ it('tests error responses', async () => {
87
+ const res = await request
88
+ .post('/graphql')
89
+ .send({ query: '{ invalidField }' });
90
+
91
+ expect(res.body.errors).toBeDefined();
92
+ });
93
+ ```
94
+
95
+ ### Server Information
96
+
97
+ The `server` object provides information about the running HTTP server:
98
+
99
+ ```typescript
100
+ const { server } = await getConnections({ schemas: ['app_public'] });
101
+
102
+ console.log(server.url); // http://localhost:5555
103
+ console.log(server.graphqlUrl); // http://localhost:5555/graphql
104
+ console.log(server.port); // 5555
105
+ console.log(server.host); // localhost
106
+
107
+ // Stop the server manually (usually handled by teardown)
108
+ await server.stop();
109
+ ```
110
+
111
+ ### Database Operations
112
+
113
+ Direct database access is available through `pg` (superuser) and `db` (app-level) clients:
114
+
115
+ ```typescript
116
+ const { pg, db } = await getConnections({ schemas: ['app_public'] });
117
+
118
+ // Superuser operations (bypasses RLS)
119
+ await pg.query('INSERT INTO app_public.users (username) VALUES ($1)', ['admin']);
120
+
121
+ // App-level operations (respects RLS)
122
+ await db.query('SELECT * FROM app_public.users');
123
+ ```
124
+
125
+ ### Seeding
126
+
127
+ Use the `seed` utilities from `pgsql-test`:
128
+
129
+ ```typescript
130
+ import { getConnections, seed } from '@constructive-io/graphql-server-test';
131
+
132
+ const { db, query, teardown } = await getConnections(
133
+ { schemas: ['app_public'] },
134
+ [
135
+ seed.sqlfile(['./sql/schema.sql', './sql/data.sql']),
136
+ seed.fn(async (client) => {
137
+ await client.query('INSERT INTO users (name) VALUES ($1)', ['Test User']);
138
+ })
139
+ ]
140
+ );
141
+ ```
142
+
143
+ ### Snapshots
144
+
145
+ Use the `snapshot` utility for snapshot testing:
146
+
147
+ ```typescript
148
+ import { getConnections, snapshot } from '@constructive-io/graphql-server-test';
149
+
150
+ it('matches snapshot', async () => {
151
+ const res = await query('{ allUsers { nodes { username } } }');
152
+ expect(snapshot(res.data)).toMatchSnapshot();
153
+ });
154
+ ```
155
+
156
+ ## Configuration Options
157
+
158
+ ### GetConnectionsInput
159
+
160
+ | Option | Type | Description |
161
+ |--------|------|-------------|
162
+ | `schemas` | `string[]` | PostgreSQL schemas to expose in GraphQL |
163
+ | `authRole` | `string` | Default role for anonymous requests |
164
+ | `useRoot` | `boolean` | Use root/superuser for queries (bypasses RLS) |
165
+ | `graphile` | `GraphileOptions` | Graphile/PostGraphile configuration |
166
+ | `server.port` | `number` | Port to run the server on (default: random) |
167
+ | `server.host` | `string` | Host to bind the server to (default: localhost) |
168
+
169
+ ## Comparison with Other Test Packages
170
+
171
+ | Package | Server | Query Method |
172
+ |---------|--------|--------------|
173
+ | `graphile-test` | None | Direct PostGraphile execution |
174
+ | `@constructive-io/graphql-test` | None | Direct PostGraphile execution |
175
+ | `@constructive-io/playwright-test` | Real HTTP | Direct PostGraphile execution |
176
+ | **`@constructive-io/graphql-server-test`** | Real HTTP | **SuperTest HTTP requests** |
177
+
178
+ ## License
179
+
180
+ MIT
181
+
182
+ ---
183
+
184
+ ## Education and Tutorials
185
+
186
+ 1. 🚀 [Quickstart: Getting Up and Running](https://constructive.io/learn/quickstart)
187
+ Get started with modular databases in minutes. Install prerequisites and deploy your first module.
188
+
189
+ 2. 📦 [Modular PostgreSQL Development with Database Packages](https://constructive.io/learn/modular-postgres)
190
+ Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
191
+
192
+ 3. ✏️ [Authoring Database Changes](https://constructive.io/learn/authoring-database-changes)
193
+ Master the workflow for adding, organizing, and managing database changes with pgpm.
194
+
195
+ 4. 🧪 [End-to-End PostgreSQL Testing with TypeScript](https://constructive.io/learn/e2e-postgres-testing)
196
+ Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
197
+
198
+ 5. ⚡ [Supabase Testing](https://constructive.io/learn/supabase)
199
+ Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
200
+
201
+ 6. 💧 [Drizzle ORM Testing](https://constructive.io/learn/drizzle-testing)
202
+ Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
203
+
204
+ 7. 🔧 [Troubleshooting](https://constructive.io/learn/troubleshooting)
205
+ Common issues and solutions for pgpm, PostgreSQL, and testing.
206
+
207
+ ## Related Constructive Tooling
208
+
209
+ ### 📦 Package Management
210
+
211
+ * [pgpm](https://github.com/constructive-io/constructive/tree/main/pgpm/pgpm): **🖥️ PostgreSQL Package Manager** for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
212
+
213
+ ### 🧪 Testing
214
+
215
+ * [pgsql-test](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-test): **📊 Isolated testing environments** with per-test transaction rollbacks—ideal for integration tests, complex migrations, and RLS simulation.
216
+ * [pgsql-seed](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-seed): **🌱 PostgreSQL seeding utilities** for CSV, JSON, SQL data loading, and pgpm deployment.
217
+ * [supabase-test](https://github.com/constructive-io/constructive/tree/main/postgres/supabase-test): **🧪 Supabase-native test harness** preconfigured for the local Supabase stack—per-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
218
+ * [graphile-test](https://github.com/constructive-io/constructive/tree/main/graphile/graphile-test): **🔐 Authentication mocking** for Graphile-focused test helpers and emulating row-level security contexts.
219
+ * [pg-query-context](https://github.com/constructive-io/constructive/tree/main/postgres/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.
220
+
221
+ ### 🧠 Parsing & AST
222
+
223
+ * [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): **🔄 SQL conversion engine** that interprets and converts PostgreSQL syntax.
224
+ * [libpg-query-node](https://www.npmjs.com/package/libpg-query): **🌉 Node.js bindings** for `libpg_query`, converting SQL into parse trees.
225
+ * [pg-proto-parser](https://www.npmjs.com/package/pg-proto-parser): **📦 Protobuf parser** for parsing PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
226
+ * [@pgsql/enums](https://www.npmjs.com/package/@pgsql/enums): **🏷️ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
227
+ * [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): **📝 Type definitions** for PostgreSQL AST nodes in TypeScript.
228
+ * [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): **🛠️ AST utilities** for constructing and transforming PostgreSQL syntax trees.
229
+
230
+ ## Credits
231
+
232
+ **🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
233
+
234
+ ## Disclaimer
235
+
236
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
237
+
238
+ 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.
@@ -0,0 +1,66 @@
1
+ import { getConnections as getPgConnections } from 'pgsql-test';
2
+ import { getEnvOptions } from '@constructive-io/graphql-env';
3
+ import { createTestServer } from './server';
4
+ import { createSuperTestAgent, createQueryFn } from './supertest';
5
+ /**
6
+ * Creates connections with an HTTP server for SuperTest testing
7
+ *
8
+ * This is the main entry point for SuperTest-based GraphQL tests. It:
9
+ * 1. Creates an isolated test database using pgsql-test
10
+ * 2. Starts a real HTTP server using @constructive-io/graphql-server
11
+ * 3. Returns a SuperTest agent and query function for making HTTP requests
12
+ * 4. Provides a teardown function to clean up everything
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * const { db, server, query, request, teardown } = await getConnections({
17
+ * schemas: ['public', 'app_public'],
18
+ * authRole: 'anonymous'
19
+ * });
20
+ *
21
+ * // Use the query function for GraphQL requests
22
+ * const res = await query(`query { allUsers { nodes { id } } }`);
23
+ *
24
+ * // Or use SuperTest directly for more control
25
+ * const res = await request
26
+ * .post('/graphql')
27
+ * .set('Authorization', 'Bearer token')
28
+ * .send({ query: '{ currentUser { id } }' });
29
+ *
30
+ * // Clean up after tests
31
+ * await teardown();
32
+ * ```
33
+ */
34
+ export const getConnections = async (input, seedAdapters) => {
35
+ // Get database connections using pgsql-test
36
+ const conn = await getPgConnections(input, seedAdapters);
37
+ const { pg, db, teardown: dbTeardown } = conn;
38
+ // Build options for the HTTP server with enableServicesApi: false
39
+ const serverOpts = getEnvOptions({
40
+ pg: pg.config,
41
+ api: {
42
+ enableServicesApi: false,
43
+ exposedSchemas: input.schemas,
44
+ defaultDatabaseId: 'test-database',
45
+ ...(input.authRole && { anonRole: input.authRole, roleName: input.authRole })
46
+ },
47
+ graphile: input.graphile
48
+ });
49
+ // Start the HTTP server using @constructive-io/graphql-server
50
+ const server = await createTestServer(serverOpts, input.server);
51
+ // Create SuperTest agent
52
+ const request = createSuperTestAgent(server);
53
+ // Combined teardown function
54
+ const teardown = async () => {
55
+ await server.stop();
56
+ await dbTeardown();
57
+ };
58
+ return {
59
+ pg,
60
+ db,
61
+ server,
62
+ request,
63
+ query: createQueryFn(request),
64
+ teardown
65
+ };
66
+ };
package/esm/index.js ADDED
@@ -0,0 +1,10 @@
1
+ // Export types
2
+ export * from './types';
3
+ // Export server utilities
4
+ export { createTestServer } from './server';
5
+ // Export SuperTest utilities
6
+ export { createSuperTestAgent } from './supertest';
7
+ // Export connection functions
8
+ export { getConnections } from './get-connections';
9
+ // Re-export seed and snapshot utilities from pgsql-test
10
+ export { seed, snapshot } from 'pgsql-test';
package/esm/server.js ADDED
@@ -0,0 +1,59 @@
1
+ import { Server } from '@constructive-io/graphql-server';
2
+ import { createServer } from 'http';
3
+ /**
4
+ * Find an available port starting from the given port
5
+ */
6
+ const findAvailablePort = async (startPort) => {
7
+ return new Promise((resolve, reject) => {
8
+ const server = createServer();
9
+ server.listen(startPort, () => {
10
+ const address = server.address();
11
+ const port = typeof address === 'object' && address ? address.port : startPort;
12
+ server.close(() => resolve(port));
13
+ });
14
+ server.on('error', (err) => {
15
+ if (err.code === 'EADDRINUSE') {
16
+ resolve(findAvailablePort(startPort + 1));
17
+ }
18
+ else {
19
+ reject(err);
20
+ }
21
+ });
22
+ });
23
+ };
24
+ /**
25
+ * Create a test server for SuperTest testing
26
+ *
27
+ * This uses the Server class from @constructive-io/graphql-server directly,
28
+ * which includes all the standard middleware (CORS, authentication, GraphQL, etc.)
29
+ */
30
+ export const createTestServer = async (opts, serverOpts = {}) => {
31
+ const host = serverOpts.host ?? 'localhost';
32
+ const requestedPort = serverOpts.port ?? 0;
33
+ const port = requestedPort === 0 ? await findAvailablePort(5555) : requestedPort;
34
+ // Merge server options into the PgpmOptions
35
+ const serverConfig = {
36
+ ...opts,
37
+ server: {
38
+ ...opts.server,
39
+ host,
40
+ port
41
+ }
42
+ };
43
+ // Create the server using @constructive-io/graphql-server
44
+ const server = new Server(serverConfig);
45
+ // Start listening and get the HTTP server
46
+ const httpServer = server.listen();
47
+ const actualPort = httpServer.address().port;
48
+ const stop = async () => {
49
+ await server.close();
50
+ };
51
+ return {
52
+ httpServer,
53
+ url: `http://${host}:${actualPort}`,
54
+ graphqlUrl: `http://${host}:${actualPort}/graphql`,
55
+ port: actualPort,
56
+ host,
57
+ stop
58
+ };
59
+ };
@@ -0,0 +1,30 @@
1
+ import { print } from 'graphql';
2
+ import supertest from 'supertest';
3
+ /**
4
+ * Create a SuperTest agent for the given server
5
+ */
6
+ export const createSuperTestAgent = (server) => {
7
+ return supertest(server.httpServer);
8
+ };
9
+ /**
10
+ * Convert a query to a string (handles both string and DocumentNode)
11
+ */
12
+ const queryToString = (query) => {
13
+ return typeof query === 'string' ? query : print(query);
14
+ };
15
+ /**
16
+ * Create a GraphQL query function
17
+ */
18
+ export const createQueryFn = (agent) => {
19
+ return async (query, variables, headers) => {
20
+ const response = await agent
21
+ .post('/graphql')
22
+ .set('Content-Type', 'application/json')
23
+ .set(headers || {})
24
+ .send({
25
+ query: queryToString(query),
26
+ variables
27
+ });
28
+ return response.body;
29
+ };
30
+ };
package/esm/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,33 @@
1
+ import type { GetConnectionOpts } from 'pgsql-test';
2
+ import type { SeedAdapter } from 'pgsql-test/seed/types';
3
+ import type { GetConnectionsInput, GetConnectionsResult } from './types';
4
+ /**
5
+ * Creates connections with an HTTP server for SuperTest testing
6
+ *
7
+ * This is the main entry point for SuperTest-based GraphQL tests. It:
8
+ * 1. Creates an isolated test database using pgsql-test
9
+ * 2. Starts a real HTTP server using @constructive-io/graphql-server
10
+ * 3. Returns a SuperTest agent and query function for making HTTP requests
11
+ * 4. Provides a teardown function to clean up everything
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * const { db, server, query, request, teardown } = await getConnections({
16
+ * schemas: ['public', 'app_public'],
17
+ * authRole: 'anonymous'
18
+ * });
19
+ *
20
+ * // Use the query function for GraphQL requests
21
+ * const res = await query(`query { allUsers { nodes { id } } }`);
22
+ *
23
+ * // Or use SuperTest directly for more control
24
+ * const res = await request
25
+ * .post('/graphql')
26
+ * .set('Authorization', 'Bearer token')
27
+ * .send({ query: '{ currentUser { id } }' });
28
+ *
29
+ * // Clean up after tests
30
+ * await teardown();
31
+ * ```
32
+ */
33
+ export declare const getConnections: (input: GetConnectionsInput & GetConnectionOpts, seedAdapters?: SeedAdapter[]) => Promise<GetConnectionsResult>;
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getConnections = void 0;
4
+ const pgsql_test_1 = require("pgsql-test");
5
+ const graphql_env_1 = require("@constructive-io/graphql-env");
6
+ const server_1 = require("./server");
7
+ const supertest_1 = require("./supertest");
8
+ /**
9
+ * Creates connections with an HTTP server for SuperTest testing
10
+ *
11
+ * This is the main entry point for SuperTest-based GraphQL tests. It:
12
+ * 1. Creates an isolated test database using pgsql-test
13
+ * 2. Starts a real HTTP server using @constructive-io/graphql-server
14
+ * 3. Returns a SuperTest agent and query function for making HTTP requests
15
+ * 4. Provides a teardown function to clean up everything
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * const { db, server, query, request, teardown } = await getConnections({
20
+ * schemas: ['public', 'app_public'],
21
+ * authRole: 'anonymous'
22
+ * });
23
+ *
24
+ * // Use the query function for GraphQL requests
25
+ * const res = await query(`query { allUsers { nodes { id } } }`);
26
+ *
27
+ * // Or use SuperTest directly for more control
28
+ * const res = await request
29
+ * .post('/graphql')
30
+ * .set('Authorization', 'Bearer token')
31
+ * .send({ query: '{ currentUser { id } }' });
32
+ *
33
+ * // Clean up after tests
34
+ * await teardown();
35
+ * ```
36
+ */
37
+ const getConnections = async (input, seedAdapters) => {
38
+ // Get database connections using pgsql-test
39
+ const conn = await (0, pgsql_test_1.getConnections)(input, seedAdapters);
40
+ const { pg, db, teardown: dbTeardown } = conn;
41
+ // Build options for the HTTP server with enableServicesApi: false
42
+ const serverOpts = (0, graphql_env_1.getEnvOptions)({
43
+ pg: pg.config,
44
+ api: {
45
+ enableServicesApi: false,
46
+ exposedSchemas: input.schemas,
47
+ defaultDatabaseId: 'test-database',
48
+ ...(input.authRole && { anonRole: input.authRole, roleName: input.authRole })
49
+ },
50
+ graphile: input.graphile
51
+ });
52
+ // Start the HTTP server using @constructive-io/graphql-server
53
+ const server = await (0, server_1.createTestServer)(serverOpts, input.server);
54
+ // Create SuperTest agent
55
+ const request = (0, supertest_1.createSuperTestAgent)(server);
56
+ // Combined teardown function
57
+ const teardown = async () => {
58
+ await server.stop();
59
+ await dbTeardown();
60
+ };
61
+ return {
62
+ pg,
63
+ db,
64
+ server,
65
+ request,
66
+ query: (0, supertest_1.createQueryFn)(request),
67
+ teardown
68
+ };
69
+ };
70
+ exports.getConnections = getConnections;
package/index.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ export * from './types';
2
+ export { createTestServer } from './server';
3
+ export { createSuperTestAgent } from './supertest';
4
+ export { getConnections } from './get-connections';
5
+ export { seed, snapshot } from 'pgsql-test';
package/index.js ADDED
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.snapshot = exports.seed = exports.getConnections = exports.createSuperTestAgent = exports.createTestServer = void 0;
18
+ // Export types
19
+ __exportStar(require("./types"), exports);
20
+ // Export server utilities
21
+ var server_1 = require("./server");
22
+ Object.defineProperty(exports, "createTestServer", { enumerable: true, get: function () { return server_1.createTestServer; } });
23
+ // Export SuperTest utilities
24
+ var supertest_1 = require("./supertest");
25
+ Object.defineProperty(exports, "createSuperTestAgent", { enumerable: true, get: function () { return supertest_1.createSuperTestAgent; } });
26
+ // Export connection functions
27
+ var get_connections_1 = require("./get-connections");
28
+ Object.defineProperty(exports, "getConnections", { enumerable: true, get: function () { return get_connections_1.getConnections; } });
29
+ // Re-export seed and snapshot utilities from pgsql-test
30
+ var pgsql_test_1 = require("pgsql-test");
31
+ Object.defineProperty(exports, "seed", { enumerable: true, get: function () { return pgsql_test_1.seed; } });
32
+ Object.defineProperty(exports, "snapshot", { enumerable: true, get: function () { return pgsql_test_1.snapshot; } });
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@constructive-io/graphql-server-test",
3
+ "version": "0.2.0",
4
+ "author": "Constructive <developers@constructive.io>",
5
+ "description": "Constructive GraphQL Server Testing with SuperTest HTTP requests",
6
+ "main": "index.js",
7
+ "module": "esm/index.js",
8
+ "types": "index.d.ts",
9
+ "homepage": "https://github.com/constructive-io/constructive",
10
+ "license": "MIT",
11
+ "publishConfig": {
12
+ "access": "public",
13
+ "directory": "dist"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/constructive-io/constructive"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/constructive-io/constructive/issues"
21
+ },
22
+ "scripts": {
23
+ "clean": "makage clean",
24
+ "prepack": "npm run build",
25
+ "build": "makage build",
26
+ "build:dev": "makage build --dev",
27
+ "lint": "eslint . --fix",
28
+ "test": "jest --passWithNoTests",
29
+ "test:watch": "jest --watch"
30
+ },
31
+ "devDependencies": {
32
+ "@types/express": "^5.0.6",
33
+ "@types/pg": "^8.16.0",
34
+ "@types/supertest": "^6.0.2",
35
+ "makage": "^0.1.10"
36
+ },
37
+ "dependencies": {
38
+ "@constructive-io/graphql-env": "^2.9.0",
39
+ "@constructive-io/graphql-server": "^2.19.2",
40
+ "@constructive-io/graphql-types": "^2.13.0",
41
+ "@pgpmjs/types": "^2.15.0",
42
+ "express": "^5.2.1",
43
+ "graphql": "15.10.1",
44
+ "pg": "^8.17.1",
45
+ "pg-cache": "^1.8.0",
46
+ "pgsql-test": "^2.26.0",
47
+ "supertest": "^7.0.0"
48
+ },
49
+ "keywords": [
50
+ "testing",
51
+ "graphql",
52
+ "graphile",
53
+ "constructive",
54
+ "supertest",
55
+ "http",
56
+ "integration",
57
+ "e2e",
58
+ "server"
59
+ ],
60
+ "gitHead": "06e19f60b9df12874808312fb999002650d6179f"
61
+ }
package/server.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ import { PgpmOptions } from '@pgpmjs/types';
2
+ import type { ServerInfo, ServerOptions } from './types';
3
+ /**
4
+ * Create a test server for SuperTest testing
5
+ *
6
+ * This uses the Server class from @constructive-io/graphql-server directly,
7
+ * which includes all the standard middleware (CORS, authentication, GraphQL, etc.)
8
+ */
9
+ export declare const createTestServer: (opts: PgpmOptions, serverOpts?: ServerOptions) => Promise<ServerInfo>;
package/server.js ADDED
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createTestServer = void 0;
4
+ const graphql_server_1 = require("@constructive-io/graphql-server");
5
+ const http_1 = require("http");
6
+ /**
7
+ * Find an available port starting from the given port
8
+ */
9
+ const findAvailablePort = async (startPort) => {
10
+ return new Promise((resolve, reject) => {
11
+ const server = (0, http_1.createServer)();
12
+ server.listen(startPort, () => {
13
+ const address = server.address();
14
+ const port = typeof address === 'object' && address ? address.port : startPort;
15
+ server.close(() => resolve(port));
16
+ });
17
+ server.on('error', (err) => {
18
+ if (err.code === 'EADDRINUSE') {
19
+ resolve(findAvailablePort(startPort + 1));
20
+ }
21
+ else {
22
+ reject(err);
23
+ }
24
+ });
25
+ });
26
+ };
27
+ /**
28
+ * Create a test server for SuperTest testing
29
+ *
30
+ * This uses the Server class from @constructive-io/graphql-server directly,
31
+ * which includes all the standard middleware (CORS, authentication, GraphQL, etc.)
32
+ */
33
+ const createTestServer = async (opts, serverOpts = {}) => {
34
+ const host = serverOpts.host ?? 'localhost';
35
+ const requestedPort = serverOpts.port ?? 0;
36
+ const port = requestedPort === 0 ? await findAvailablePort(5555) : requestedPort;
37
+ // Merge server options into the PgpmOptions
38
+ const serverConfig = {
39
+ ...opts,
40
+ server: {
41
+ ...opts.server,
42
+ host,
43
+ port
44
+ }
45
+ };
46
+ // Create the server using @constructive-io/graphql-server
47
+ const server = new graphql_server_1.Server(serverConfig);
48
+ // Start listening and get the HTTP server
49
+ const httpServer = server.listen();
50
+ const actualPort = httpServer.address().port;
51
+ const stop = async () => {
52
+ await server.close();
53
+ };
54
+ return {
55
+ httpServer,
56
+ url: `http://${host}:${actualPort}`,
57
+ graphqlUrl: `http://${host}:${actualPort}/graphql`,
58
+ port: actualPort,
59
+ host,
60
+ stop
61
+ };
62
+ };
63
+ exports.createTestServer = createTestServer;
package/supertest.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ import supertest from 'supertest';
2
+ import type { ServerInfo, GraphQLQueryFn } from './types';
3
+ /**
4
+ * Create a SuperTest agent for the given server
5
+ */
6
+ export declare const createSuperTestAgent: (server: ServerInfo) => supertest.Agent;
7
+ /**
8
+ * Create a GraphQL query function
9
+ */
10
+ export declare const createQueryFn: (agent: supertest.Agent) => GraphQLQueryFn;
package/supertest.js ADDED
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createQueryFn = exports.createSuperTestAgent = void 0;
7
+ const graphql_1 = require("graphql");
8
+ const supertest_1 = __importDefault(require("supertest"));
9
+ /**
10
+ * Create a SuperTest agent for the given server
11
+ */
12
+ const createSuperTestAgent = (server) => {
13
+ return (0, supertest_1.default)(server.httpServer);
14
+ };
15
+ exports.createSuperTestAgent = createSuperTestAgent;
16
+ /**
17
+ * Convert a query to a string (handles both string and DocumentNode)
18
+ */
19
+ const queryToString = (query) => {
20
+ return typeof query === 'string' ? query : (0, graphql_1.print)(query);
21
+ };
22
+ /**
23
+ * Create a GraphQL query function
24
+ */
25
+ const createQueryFn = (agent) => {
26
+ return async (query, variables, headers) => {
27
+ const response = await agent
28
+ .post('/graphql')
29
+ .set('Content-Type', 'application/json')
30
+ .set(headers || {})
31
+ .send({
32
+ query: queryToString(query),
33
+ variables
34
+ });
35
+ return response.body;
36
+ };
37
+ };
38
+ exports.createQueryFn = createQueryFn;
package/types.d.ts ADDED
@@ -0,0 +1,74 @@
1
+ import type { Server } from 'http';
2
+ import type { DocumentNode, GraphQLError } from 'graphql';
3
+ import type { PgTestClient } from 'pgsql-test/test-client';
4
+ import type { GraphileOptions } from '@constructive-io/graphql-types';
5
+ import type supertest from 'supertest';
6
+ /**
7
+ * Options for creating a test server
8
+ */
9
+ export interface ServerOptions {
10
+ /** Port to run the server on (defaults to random available port) */
11
+ port?: number;
12
+ /** Host to bind the server to (defaults to localhost) */
13
+ host?: string;
14
+ }
15
+ /**
16
+ * Server information returned by createTestServer
17
+ */
18
+ export interface ServerInfo {
19
+ /** The HTTP server instance */
20
+ httpServer: Server;
21
+ /** The base URL of the server (e.g., http://localhost:5555) */
22
+ url: string;
23
+ /** The GraphQL endpoint URL (e.g., http://localhost:5555/graphql) */
24
+ graphqlUrl: string;
25
+ /** The port the server is running on */
26
+ port: number;
27
+ /** The host the server is bound to */
28
+ host: string;
29
+ /** Stop the server */
30
+ stop: () => Promise<void>;
31
+ }
32
+ /**
33
+ * Input options for getConnections
34
+ */
35
+ export interface GetConnectionsInput {
36
+ /** Use root/superuser for queries (bypasses RLS) */
37
+ useRoot?: boolean;
38
+ /** PostgreSQL schemas to expose in GraphQL */
39
+ schemas: string[];
40
+ /** Default role for anonymous requests */
41
+ authRole?: string;
42
+ /** Graphile/PostGraphile configuration options */
43
+ graphile?: GraphileOptions;
44
+ /** Server configuration options */
45
+ server?: ServerOptions;
46
+ }
47
+ /**
48
+ * GraphQL response structure
49
+ */
50
+ export interface GraphQLResponse<T> {
51
+ data?: T;
52
+ errors?: readonly GraphQLError[];
53
+ }
54
+ /**
55
+ * GraphQL query function type
56
+ */
57
+ export type GraphQLQueryFn = <TResult = any, TVariables = Record<string, any>>(query: string | DocumentNode, variables?: TVariables, headers?: Record<string, string>) => Promise<GraphQLResponse<TResult>>;
58
+ /**
59
+ * Result from getConnections
60
+ */
61
+ export interface GetConnectionsResult {
62
+ /** PostgreSQL client for superuser operations (bypasses RLS) */
63
+ pg: PgTestClient;
64
+ /** PostgreSQL client for app-level operations (respects RLS) */
65
+ db: PgTestClient;
66
+ /** Server information including URL and stop function */
67
+ server: ServerInfo;
68
+ /** Raw SuperTest agent for custom HTTP requests */
69
+ request: supertest.Agent;
70
+ /** GraphQL query function */
71
+ query: GraphQLQueryFn;
72
+ /** Teardown function to clean up database and server */
73
+ teardown: () => Promise<void>;
74
+ }
package/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });