Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A Cypress database error is fixed fastest when you first identify which process made the failed connection. A cy.task() failure points to Cypress’s Node process, task registration, credentials, or its route to the database. An application startup failure belongs to the backend environment. A browser or Cypress console ECONNREFUSED may instead be a Cypress/browser debugging connection and have nothing to do with the database.

Use the workflow below to identify the owner, reproduce the same connection outside the test, then correct only the failing layer.

1. Identify the process that owns the failure

Save the complete terminal output, stack trace, database client error, host, port, and the command that started Cypress. Note whether the error appears while Cypress loads its configuration, when a cy.task() runs, while the application starts, or during a browser request.

Failure during cy.task()

The task is running in Node, outside the browser. Typical owners are a missing task registration, an unavailable environment variable, an uninstalled client library, an incorrect endpoint, or a network path unavailable to the Node process.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Failure while the application starts

Your backend, not Cypress, is opening the database connection. Check the application’s own logs, configuration, container network, readiness checks, and database permissions. Cypress can only report the resulting application failure.

Failure in browser or Cypress console traffic

A refused connection can be Cypress’s browser or remote-debugging channel, a web server that is not listening, or a proxy/VPN problem. Do not change database credentials until you establish that the failing socket belongs to the database.

2. Turn the error into a reproducible fact

  1. Run the same test locally from the project root and record whether it passes.
  2. Run the database client or a minimal Node script from the same shell, container, or CI step that launches Cypress.
  3. Print safe diagnostics: database host (not the password), resolved environment names, Node version, working directory, and whether the service hostname resolves. Never print connection strings containing secrets.
  4. Compare the failing run with a working run: Node version, lockfile installation, environment-variable scope, container network, VPN/proxy, firewall rules, and database readiness.

“Works on my machine” is useful evidence: it usually means the CI process has different configuration or network reachability, not that Cypress changes database protocols.

3. Put direct database work in a Node task

Cypress registers Node-side work in setupNodeEvents. That hook runs in an independent child process using the Node version that launched Cypress, with the project as its working directory. Browser test code should request the work with cy.task() rather than importing a database driver into the browser bundle.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Example configuration

const { defineConfig } = require('cypress');
const { Client } = require('pg');

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('task', {
        async resetDatabase() {
          const client = new Client({
            host: process.env.DB_HOST,
            port: Number(process.env.DB_PORT),
            database: process.env.DB_NAME,
            user: process.env.DB_USER,
            password: process.env.DB_PASSWORD,
            ssl: process.env.DB_SSL === 'true' ? { rejectUnauthorized: false } : undefined
          });

          await client.connect();
          try {
            await client.query('TRUNCATE TABLE orders, users RESTART IDENTITY CASCADE');
            return null;
          } finally {
            await client.end();
          }
        }
      });

      return config;
    }
  }
});

Replace the driver and SQL with those for your database. The important Cypress details are the exact task name, Node-side registration, and returning a value or null. A handler that resolves to undefined fails the task because Cypress treats that result as a possible missing handler.

Call the task from a spec

describe('orders', () => {
  beforeEach(() => {
    cy.task('resetDatabase');
  });

  it('shows an empty order list', () => {
    cy.visit('/orders');
    cy.contains('No orders').should('be.visible');
  });
});

If Cypress says the task is not handled, compare resetDatabase character-for-character in the spec and configuration, confirm the configuration file is the one this run loads, and restart Cypress after changing it.

Use an external database CLI safely

When a task invokes a migration or reset executable, use an argument array instead of constructing a shell command string. This avoids quoting mistakes and reduces differences in shell behavior and PATH between local and CI runs.

const { execFileSync } = require('node:child_process');

on('task', {
  migrateDatabase() {
    execFileSync('your-db-cli', ['migrate', '--env', 'test'], {
      stdio: 'inherit',
      env: process.env
    });
    return null;
  }
});

4. Verify configuration and secrets in the failing process

Environment variables available to your application container are not automatically available to the process launching Cypress. In CI, place test-only variables in the job or step that runs Cypress, and ensure the variable names match the task code exactly. Confirm that the CI secret is exposed to the correct branch, fork, or environment; many systems intentionally withhold secrets from untrusted pull requests.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Check for an empty variable versus an unset variable; both can produce misleading authentication or host errors.
  • Convert numeric ports explicitly and reject NaN before opening the client.
  • Do not hard-code production credentials in cypress.config.* or commit a local .env file.
  • Install the database client in the project dependency set used by CI, not only in a developer’s global environment.

5. Test the network from the right location

A hostname that works on your laptop may not resolve inside a CI container. Test DNS, routing, firewall policy, TLS requirements, and database allow-lists from the exact Node process environment. Also verify that the database is ready before Cypress starts: a container can be running while its listener is still initializing.

For a task, the path is Cypress Node process → database endpoint. For an application failure, it is application process → database endpoint. For a browser request, it is browser → application/API. Check the corresponding logs and network policy instead of applying a generic “open the database port” fix.

Read the error class carefully

  • Connection refused: the destination is reachable but no service accepted the socket, or a firewall actively rejected it. Check host, port, listener, and readiness.
  • Timeout: routing, firewall, VPN, security software, or an incorrect private hostname is more likely than a bad password.
  • Authentication failure: the server was reached; inspect username, password, database name, authentication mechanism, and secret scope.
  • TLS or certificate error: verify the server’s required encryption mode and trust chain. Do not disable certificate verification permanently just to make a test pass.
  • DNS resolution error: use the service name visible from the failing container or runner, not a hostname that exists only on a developer workstation.

6. Add Cypress diagnostics without confusing subsystems

Cypress supports debug logging by namespace. Enable the task namespace, cypress:server:task, when investigating registration and task execution; enable relevant request or network namespaces when diagnosing application traffic. Capture the logs in CI artifacts so a failed run can be compared with a successful one.

These logs show where Cypress stopped, not whether the database accepted a connection. Pair them with application logs and database-side connection or audit logs. A cloud replay of a failed test can show application state, requests, and browser console output, but it cannot prove that database credentials were valid or replace database diagnostics.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

7. Choose the least coupled test strategy

Approach Use it when What it exercises Diagnostic boundary
cy.intercept() stubbing The test needs a controlled frontend response, not persistence Browser/UI behavior against a stubbed request Cypress test and browser setup
cy.request() to a backend The test needs API interaction or seeding through an application endpoint Backend API behavior and service access Cypress-to-application network path
cy.task() with a Node client or CLI The test must reset, seed, or query the database directly Database operations from Cypress’s Node process Task registration, Node environment, client, and Node-to-database network path

Use stubbing when persistence is outside the test’s purpose. Use an API when the application’s validation and authorization should run. Use a direct task when the test deliberately verifies real database state. These are design choices, not interchangeable connection fixes.

8. CI-specific checks

  1. Confirm the Cypress binary and cache are installed in the same job that runs tests; print cache information when diagnosing installation or environment drift.
  2. Start the database and wait for a real readiness condition, not merely a process or container status.
  3. Use the CI service hostname and network alias visible to the test job. localhost inside a container refers to that container, not necessarily the database service.
  4. Ensure migrations and seed tasks finish before the first spec. A long-running task blocks subsequent Cypress commands, so keep resets bounded and fail with a useful timeout.
  5. When only CI fails, preserve the task logs, application logs, and database logs for the same timestamp window.

9. Troubleshooting branches

The task name is reported as unknown

Check that setupNodeEvents is in the active configuration, the event handler is registered before returning config, and the spec uses the exact name. A task that returns undefined must also be changed to return a useful value or null.

The client package cannot be found

Add the driver to the project’s declared dependencies, reinstall from the lockfile in CI, and verify that the configuration is loaded from the expected project directory.

Local passes but CI refuses or times out

Compare endpoint names, secret availability, container networks, firewall rules, VPN/proxy assumptions, and database readiness. Run a minimal connectivity check in the same CI step rather than from a separate diagnostic machine.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The browser shows ECONNREFUSED

First identify the port and process in the stack trace. If it is Cypress’s browser/debugging channel or the web server, investigate firewall, proxy/VPN interception, security software, browser launch arguments, and whether Electron reproduces the problem. Do not treat that message alone as evidence of a database outage.

Reset tasks make the suite very slow

Cypress waits for each cy.task() to finish before running later commands. Keep database work targeted, close clients in a finally block, avoid unnecessary full rebuilds, and move expensive one-time setup to a controlled CI stage when test isolation permits.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If the separate problem is capturing a clean screenshot of a failing Cypress page for a CI report, ScreenshotNeo can do it with one HTTP request. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be disabled. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.

See the parameter reference in the ScreenshotNeo documentation. This cURL request returns a WebP file:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Equivalent Python:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Equivalent Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

There is a free allowance of 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 screenshots, and every feature is included on every plan. Create a free ScreenshotNeo account.

FAQ

Can browser test code open a database connection directly?

Keep database drivers and credentials in Node-side tasks or your backend. Browser code should call a task or API so secrets are not bundled into the page.

Should every end-to-end test reset the database?

No. Reset only when isolation or deterministic data requires it; otherwise use an API seed, fixtures, or stubs that match the test’s purpose.

Does Cypress Cloud prove the database was reachable?

No. Replay can show browser and application context. Database and task logs are still required to establish the connection result.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Can browser test code open a database connection directly?

Keep database drivers and credentials in Node-side tasks or your backend. Browser code should call a task or API so secrets are not bundled into the page.

Should every end-to-end test reset the database?

No. Reset only when isolation or deterministic data requires it; otherwise use an API seed, fixtures, or stubs that match the test’s purpose.

Does Cypress Cloud prove the database was reachable?

No. Replay can show browser and application context. Database and task logs are still required to establish the connection result.

The Bottom Line

Find the process that owns the socket first. Then validate task registration, Node-side configuration, CI secrets, readiness, and network reachability from that exact process. Choose cy.intercept(), cy.request(), or cy.task() according to what the test must prove.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.