Cypress PostgreSQL Database Integration

1.0.8 · abandoned · verified Sun Apr 19

This package provides a set of Cypress commands and plugin utilities for interacting directly with a PostgreSQL database during end-to-end tests. It allows test suites to execute SQL queries, verify data, or seed test data by leveraging the `pg` client library. The current stable version is 1.0.8. Based on the README, it appears to support older Cypress plugin architectures (e.g., `cypress/plugins/index.js`), which suggests it is not actively maintained for the latest Cypress versions (Cypress 10+ uses `cypress.config.js`). Its primary differentiation is enabling direct database interaction within Cypress tests, streamlining data setup and verification workflows, offering a direct bridge for database operations within the Cypress testing environment, which can be critical for test data management and assertions.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to configure `cypress-postgresql` in a Cypress setup (pre-Cypress 10.0), define database credentials, load custom commands, and execute a basic insert and select query within a test.

/* cypress.json or cypress.config.js equivalent */
{
  "db": {
    "user": "process.env.PG_USER ?? ''",
    "password": "process.env.PG_PASSWORD ?? ''",
    "host": "localhost",
    "port": 5432,
    "database": "test_db"
  }
}

/* cypress/plugins/index.js (Cypress < 10) or cypress.config.js setup */
const postgreSQL = require('cypress-postgresql');
const { Pool } = require('pg');
const dbConfig = require('../../cypress.json'); // Adjust path as needed

module.exports = (on, config) => {
  const pool = new Pool(dbConfig.db);
  const tasks = postgreSQL.loadDBPlugin(pool);
  on('task', tasks);
  return config;
};

/* cypress/support/commands.js */
import postgreSQL from 'cypress-postgresql';
postgreSQL.loadDBCommands();

/* cypress/e2e/db.cy.js */
describe('Database interactions', () => {
  beforeEach(() => {
    // Ensure the database is clean or seeded before each test
    cy.postgresql('TRUNCATE TABLE users RESTART IDENTITY;').then(() => {
      cy.log('Users table truncated.');
    });
  });

  it('should insert and retrieve data from PostgreSQL', () => {
    cy.postgresql(`INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com');`)
      .then(() => {
        return cy.postgresql(`SELECT name FROM users WHERE email = 'john@example.com';`);
      })
      .then((result) => {
        expect(result[0].name).to.eq('John Doe');
      });
  });
});

view raw JSON →