CodeceptJS Database Helper

1.2.2 · active · verified Wed Apr 22

CodeceptJS Database Helper (codeceptjs-dbhelper) is a utility designed to integrate database interaction directly into CodeceptJS end-to-end and integration tests. It leverages the 'database-js' library and its various drivers, allowing testers to execute SQL queries or database commands to prepare and clean up test data efficiently. This helper is particularly useful for managing database state before and after test case execution, ensuring test isolation and consistent environments. The current stable version is 1.2.2, with releases typically tied to bug fixes or minor enhancements like improved JSDoc and TypeScript definitions (added in v1.1.0). A key differentiator is its compatibility across CodeceptJS versions 1, 2, and 3, and its reliance on the flexible 'database-js' ecosystem for connecting to a wide array of database types, including MySQL, PostgreSQL, SQLite, MS SQL Server, and even file-based sources like CSV and Excel. It simplifies database operations within the test runner's context without requiring direct database client imports in individual test files.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates connecting to a database (MySQL example), seeding test data before the test suite and individual tests, cleaning up connections, and executing queries within a CodeceptJS scenario using the DbHelper methods available on the `I` object.

const { BeforeSuite, AfterSuite, Before, Scenario } = require('codeceptjs');

BeforeSuite(async ({ I }) => {
  // Establish a database connection named 'testdb'
  // Replace connection string with your actual database details and credentials
  I.connect("testdb", `mysql://root:password@localhost:3306/testdb`);
});

AfterSuite(async ({ I }) => {
  // Close the database connection named 'testdb'
  await I.removeConnection("testdb");
});

Before(async ({ I }) => {
  // Clean up and seed the 'user' table before each test for a clean state
  await I.run("testdb", "DELETE FROM user");
  await I.run("testdb", "INSERT INTO user (username, password) VALUES (?, ?)", "admin", "123456");
  await I.run("testdb", "INSERT INTO user (username, password) VALUES (?, ?)", "bob", "654321");
});

Scenario('should retrieve a specific user from the database', async ({ I }) => {
  // Execute a query to retrieve users and perform assertions
  const users = await I.run("testdb", "SELECT username FROM user WHERE username = ?", "admin");

  console.log('Found users:', users);
  I.assert(users.length).equals(1);
  I.assert(users[0].username).equals('admin');

  const nonExistentUser = await I.run("testdb", "SELECT username FROM user WHERE username = ?", "charlie");
  I.assert(nonExistentUser.length).equals(0);
});

view raw JSON →