{"id":16315,"library":"codeceptjs-dbhelper","title":"CodeceptJS Database Helper","description":"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.","status":"active","version":"1.2.2","language":"javascript","source_language":"en","source_url":"https://github.com/thiagodp/codeceptjs-dbhelper","tags":["javascript","codeceptjs","database","database-js"],"install":[{"cmd":"npm install codeceptjs-dbhelper","lang":"bash","label":"npm"},{"cmd":"yarn add codeceptjs-dbhelper","lang":"bash","label":"yarn"},{"cmd":"pnpm add codeceptjs-dbhelper","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core database abstraction layer required for all database operations. Users must install this package along with a specific database driver.","package":"database-js","optional":false},{"reason":"Driver for MySQL database connectivity. Users must install the specific driver for their chosen database type.","package":"database-js-mysql","optional":true},{"reason":"Driver for PostgreSQL database connectivity. Users must install the specific driver for their chosen database type.","package":"database-js-postgres","optional":true},{"reason":"Driver for SQLite database connectivity. Users must install the specific driver for their chosen database type.","package":"database-js-sqlite","optional":true}],"imports":[{"note":"The DbHelper is a CodeceptJS plugin loaded via the `helpers` configuration in `codecept.conf.js`. It does not expose symbols for direct import into test files. Its methods are mixed into the CodeceptJS `I` object. The 'host' and 'user' parameters are examples of common configuration properties.","wrong":"import { DbHelper } from 'codeceptjs-dbhelper';","symbol":"DbHelper Configuration","correct":"{\n  \"helpers\": {\n    \"DbHelper\": {\n      \"require\": \"codeceptjs-dbhelper\",\n      \"host\": \"localhost\",\n      \"user\": \"root\"\n    }\n  }\n}"},{"note":"Methods like `connect` are made available on the CodeceptJS `I` object after the DbHelper is configured. They are not imported directly from 'codeceptjs-dbhelper', but rather used within CodeceptJS test files.","symbol":"I.connect","correct":"I.connect(\"mydb\", \"mysql://user:pass@host:port/dbname\");"},{"note":"Database commands and queries are executed via `I.run`, using a connection key established with `I.connect`. Parameters are passed securely to prevent SQL injection, adhering to `database-js` conventions.","symbol":"I.run","correct":"await I.run(\"mydb\", \"SELECT * FROM users WHERE id = ?\", userId);"}],"quickstart":{"code":"const { BeforeSuite, AfterSuite, Before, Scenario } = require('codeceptjs');\n\nBeforeSuite(async ({ I }) => {\n  // Establish a database connection named 'testdb'\n  // Replace connection string with your actual database details and credentials\n  I.connect(\"testdb\", `mysql://root:password@localhost:3306/testdb`);\n});\n\nAfterSuite(async ({ I }) => {\n  // Close the database connection named 'testdb'\n  await I.removeConnection(\"testdb\");\n});\n\nBefore(async ({ I }) => {\n  // Clean up and seed the 'user' table before each test for a clean state\n  await I.run(\"testdb\", \"DELETE FROM user\");\n  await I.run(\"testdb\", \"INSERT INTO user (username, password) VALUES (?, ?)\", \"admin\", \"123456\");\n  await I.run(\"testdb\", \"INSERT INTO user (username, password) VALUES (?, ?)\", \"bob\", \"654321\");\n});\n\nScenario('should retrieve a specific user from the database', async ({ I }) => {\n  // Execute a query to retrieve users and perform assertions\n  const users = await I.run(\"testdb\", \"SELECT username FROM user WHERE username = ?\", \"admin\");\n\n  console.log('Found users:', users);\n  I.assert(users.length).equals(1);\n  I.assert(users[0].username).equals('admin');\n\n  const nonExistentUser = await I.run(\"testdb\", \"SELECT username FROM user WHERE username = ?\", \"charlie\");\n  I.assert(nonExistentUser.length).equals(0);\n});","lang":"javascript","description":"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."},"warnings":[{"fix":"Run `npm i -D database-js database-js-YOUR_DRIVER_NAME` (e.g., `npm i -D database-js database-js-mysql`) in addition to `npm i -D codeceptjs-dbhelper`.","message":"The DbHelper relies on the `database-js` abstraction layer and specific database drivers. You must manually install `database-js` and the chosen driver (e.g., `database-js-mysql`, `database-js-sqlite`) separately from the helper itself.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Update your CodeceptJS test files to use object destructuring for the `I` object in callbacks: `async ({ I }) => { /* ... */ }`. Refer to the CodeceptJS upgrade documentation for more information.","message":"When upgrading CodeceptJS from version 2 to 3, the argument signature for `Scenario`, `Before`, and `After` callbacks changed. CodeceptJS 2 passes `I` directly (e.g., `async (I) => { ... }`), while CodeceptJS 3 requires `I` to be destructured from an object (e.g., `async ({ I }) => { ... }`).","severity":"gotcha","affected_versions":">=1.0.0 (when used with CodeceptJS v3)"},{"fix":"Verify the connection string syntax according to your chosen `database-js` driver documentation and confirm network access. It is recommended to use environment variables for sensitive credentials.","message":"Ensure your database connection strings are correctly formatted and accessible from the environment where CodeceptJS tests are running. Common issues include incorrect host, port, username, password, or database name, as well as network/firewall restrictions.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Install the required database driver using npm: `npm i -D database-js-YOUR_DRIVER_NAME`. For example, `npm i -D database-js-mysql`.","cause":"A specific database driver for 'database-js' (e.g., 'database-js-mysql') was not installed, but its connection string was used.","error":"Error: Cannot find module 'database-js-mysql'"},{"fix":"Verify that `codeceptjs-dbhelper` is listed in the `helpers` section of your `codecept.conf.js` file with the correct `require` path, typically `\"require\": \"codeceptjs-dbhelper\"`.","cause":"The `DbHelper` was not correctly configured in your `codecept.conf.js` file, or CodeceptJS failed to load it.","error":"TypeError: I.connect is not a function"},{"fix":"Check the database file path in your connection string and ensure the test runner has read/write permissions to that directory. Use an absolute path if necessary for clarity.","cause":"The specified path for a SQLite database file in the connection string is incorrect, or there are insufficient file system permissions to create/access the file.","error":"Error: SQLITE_CANTOPEN: unable to open database file"}],"ecosystem":"npm"}