How do you use SQL in automated tests?
In automated tests SQL prepares data, checks what the client cannot see and cleans up by a marker; the query runs in Node. Cypress uses cy.task, because the test runs in the browser, while Playwright connects to the database straight from the test. The pg driver returns NUMERIC and BIGINT as strings and cy.task is not retried, so a write is awaited with a recursive call in Cypress and expect.poll in Playwright.
SQL · QA practice
Cypress cannot connect to a database directly. Where does the SQL run and what goes into the test?
A Cypress test clicks a button and must check a row in the database. But import { Client } from 'pg' in the test file does not work: the test code runs in the browser, and a connection to PostgreSQL is a TCP connection a browser does not open. Playwright does not have this problem, but has others: the time of the write, the number type and the connection lifecycle. This lesson is about how SQL gets into automated tests in both tools and which rules give stable checks.
How it works and why
In Cypress the configuration runs in a separate Node.js process. A task is added there by name, and the test calls it with the cy.task command: the arguments are serialised and passed to the Node process, the code with the database driver runs there, and the result goes back to the browser. A task must return a value: Cypress treats undefined as an error, so return null or an array of rows. Playwright runs tests in Node.js right away, so the database client connects directly, conveniently through a fixture that opens a connection pool once per worker.
The path of an SQL query from a Cypress test
Example: checking a record after a click
Cypress: the task in the config and the call in the test.
// cypress.config.ts
import { defineConfig } from 'cypress';
import { Pool } from 'pg';
const pool = new Pool({ connectionString: process.env.DB_URL });
export default defineConfig({
e2e: {
setupNodeEvents(on) {
on('task', {
async dbQuery({ sql, params }: { sql: string; params?: unknown[] }) {
const res = await pool.query(sql, params);
return res.rows;
},
});
},
},
});
cy.contains('button', 'Top up 500').click();
// cy.task is not retried: .should checks what was already returned
cy.task('dbQuery', {
sql: 'SELECT COUNT(*)::int AS n FROM transactions WHERE account_id = $1',
params: [10],
}).its('0.n').should('eq', 1);
Playwright: a fixture and a test with polling.
// fixtures.ts
import { test as base, expect } from '@playwright/test';
import { Pool } from 'pg';
export const test = base.extend<{}, { db: Pool }>({
db: [
async ({}, use) => {
const pool = new Pool({ connectionString: process.env.DB_URL });
await use(pool);
await pool.end();
},
{ scope: 'worker' }, // one connection pool per worker
],
});
export { expect };
test('top-up is saved once', async ({ page, db }) => {
await page.goto('/wallet');
await page.getByRole('button', { name: 'Top up 500' }).click();
// polling, not a pause: the record may appear with a delay
await expect
.poll(async () => {
const { rows } = await db.query(
'SELECT COUNT(*)::int AS n FROM transactions WHERE account_id = $1',
[10],
);
return rows[0].n;
})
.toBe(1);
});
Two small things on which first attempts break. First, the pg driver returns NUMERIC and BIGINT (including the result of COUNT(*)) as strings so as not to lose precision, so expect(rows[0].balance).toBe(750) fails because the value is '750.00'. Hence COUNT(*)::int in the examples, and sums are compared to a string or converted explicitly. Second, cy.task is a command, not a query: .should after it does not repeat the task itself. So waiting for a record in Cypress is written as a recursive function that calls the task again until success or a timeout, while in Playwright it is expect.poll.
Limits and alternatives
A test that goes into the database is tied to the schema: renaming a table breaks it, although nothing changed for the user. So the database is used where the client sees nothing, and the rest is checked through the API or the UI. Rules that make such tests maintainable: a separate database user for tests with minimal rights (read, and write only in a test schema); the password and address in environment variables, not in the repository; the test creates its own data and does not depend on another test's data; cleanup by marker in a teardown hook; one connection or pool, not a new connection per query. The default cy.task timeout is 60 seconds (taskTimeout), so a slow query is visible at once.
Common mistakes
- Importing a database driver directly into a Cypress test file: the code runs in the browser and does not bundle.
- A task with no
return: Cypress reports that the task did not return a value. - Comparing
NUMERICwith a number: the driver returns a string. - A query right after a click with no waiting: the test is unstable on a slow CI.
- An SQL string built from the test's input instead of parameters: the same risks as in the application.
- Database credentials in the test code or the repository.
Check yourself
In a test expect(rows[0].balance).toBe(750) fails with Expected 750, Received "750.00". Why and what to do?
Answer
The pg driver returns NUMERIC as a string so as not to lose precision. Compare with the string '750.00', or cast the type in the query, or parse the number explicitly, keeping in mind that for money exact decimal arithmetic is better than float.
A Cypress test checks a record with cy.task(...).its('0.n').should('eq', 1) but on CI sometimes sees 0. Why does the retry not help?
Answer
cy.task is a command: it runs once, and .should repeats only the check of the value already received. A recursive function is needed that calls the task again until it gets 1 or time runs out.