CodeceptJS PostgreSQL Helper
CodeceptJS helper (version 1.0.1) designed to streamline end-to-end testing against PostgreSQL databases. This package allows developers to execute raw SQL queries directly from their CodeceptJS test scenarios, which is crucial for setting up test data, verifying database states, and cleaning up after tests. It integrates into the CodeceptJS ecosystem by being configured in `codecept.conf.js` and exposing its methods via the framework's actor object (`I`). This helper differentiates itself from general PostgreSQL client libraries by providing a test-centric interface within the CodeceptJS testing paradigm. The project is maintained by Percona-Lab, with its release cadence currently driven by community contributions and specific project needs.
Common errors
-
Error: connect ECONNREFUSED 127.0.0.1:5432
cause The CodeceptJS helper could not establish a connection to the PostgreSQL server at the specified host and port.fixVerify that the PostgreSQL server is running, listening on the specified port (`5432` by default), and accessible from the machine running CodeceptJS tests. Check firewall rules if applicable. Confirm `host` and `port` in `codecept.conf.js`. -
Error: password authentication failed for user "postgres"
cause The provided username or password in the helper configuration is incorrect for the PostgreSQL database.fixDouble-check the `user` and `password` values in `codecept.conf.js` against your PostgreSQL user credentials. Ensure the user has permissions to connect to the specified database. -
Error: database "testdb" does not exist
cause The specified database name in the helper configuration does not exist on the PostgreSQL server.fixEnsure the `database` name in `codecept.conf.js` matches an existing database on your PostgreSQL server, or create the database if it's missing.
Warnings
- gotcha Directly embedding sensitive database credentials (host, port, user, password, database) into `codecept.conf.js` is a security risk. These values should be externalized, especially in shared or CI/CD environments.
- gotcha Constructing SQL queries by directly concatenating unsanitized string inputs (e.g., from user input or external sources) can lead to SQL injection vulnerabilities.
- breaking This package is a CodeceptJS helper and is designed to run within the CodeceptJS framework. It cannot be used as a standalone Node.js PostgreSQL client library.
- gotcha Ensure your PostgreSQL database server is running and accessible from where CodeceptJS tests are executed. Network firewalls or incorrect host/port configurations can prevent connections.
Install
-
npm install codeceptjs-postgresqlhelper -
yarn add codeceptjs-postgresqlhelper -
pnpm add codeceptjs-postgresqlhelper
Imports
- PostgresqlDBHelper Class
const PostgresqlDBHelper = require('codeceptjs-postgresqlhelper'); - Configuration `require`
import { PostgresqlDBHelper } from 'codeceptjs-postgresqlhelper';helpers: { PostgresqlDBHelper: { require: 'codeceptjs-postgresqlhelper', // ... configuration options } } - I.runQuery (in tests)
await I.runQuery('SELECT * FROM my_table;');
Quickstart
const { setHeadlessWhen, setWindowSize } = require('@codeceptjs/configure');
setHeadlessWhen(process.env.CI);
setWindowSize(1200, 800);
exports.config = {
tests: './*_test.js',
output: './output',
helpers: {
PostgresqlDBHelper: {
require: 'codeceptjs-postgresqlhelper',
host: process.env.DB_HOST ?? '127.0.0.1',
port: parseInt(process.env.DB_PORT ?? '5432'),
user: process.env.DB_USER ?? 'postgres',
password: process.env.DB_PASSWORD ?? 'postgres',
database: process.env.DB_DATABASE ?? 'testdb',
},
// Include another helper if browser interaction is needed, e.g., Playwright
// Playwright: {
// url: 'http://localhost',
// show: true,
// browser: 'chromium'
// }
},
include: {},
bootstrap: async () => {
// Optional: run initial setup like creating the database if it doesn't exist
// (requires a separate connection for initial DB creation)
},
teardown: null,
mocha: {},
name: 'codeceptjs-postgresqlhelper-quickstart',
plugins: {
retryFailedStep: { enabled: true },
screenshotOnFail: { enabled: true }
}
};
// --- my_db_test.js ---
Feature('Database Operations');
Scenario('should create a table, insert data, and verify', async ({ I }) => {
const tableName = 'test_users_' + Date.now();
const username = 'john_doe_' + Date.now();
const email = username + '@example.com';
// 1. Create a table
await I.runQuery(`CREATE TABLE IF NOT EXISTS ${tableName} (id SERIAL PRIMARY KEY, username VARCHAR(255) UNIQUE, email VARCHAR(255));`);
console.log(`Table ${tableName} created or already exists.`);
// 2. Insert data
await I.runQuery(`INSERT INTO ${tableName} (username, email) VALUES ('${username}', '${email}');`);
console.log(`Inserted user ${username}.`);
// 3. Verify data insertion
const selectResult = await I.runQuery(`SELECT * FROM ${tableName} WHERE username = '${username}';`);
I.assert(selectResult.rows.length).equals(1);
I.assert(selectResult.rows[0].email).equals(email);
console.log(`Verified user ${username} in table.`);
// 4. Clean up (optional, but good practice for isolated tests)
await I.runQuery(`DROP TABLE ${tableName};`);
console.log(`Table ${tableName} dropped.`);
});