QA Interview Hub · Knowledge base · Quizzes · Українська

Cypress › Framework architecture

What are cy.task and setupNodeEvents?

A test runs in the browser with no access to a database or files, so cy.task provides the bridge into Node. The function is registered in setupNodeEvents through on('task', {...}) and the test calls it by name. The argument is serialised, so one object is passed, and the task must return a value, a Promise or null. Dangerous tasks such as a reset are tied to the test database.

Cypress · Patterns and data

The test clicked "Pay". How do you check that the order in the database really became paid?

The interface showed "Paid", but QA wants to know what is written in the database, and also to reset data before the test. Writing import { Client } from 'pg' straight in a spec will not work: test code runs in the browser, which has no sockets to a database and no file system. cy.task and setupNodeEvents provide a bridge into Node. This lesson covers how the bridge works, what you can pass and return, and its limits.

How it works and why. Cypress consists of two processes. The spec runs inside the browser next to the application. Separately runs Cypress's Node process, which reads cypress.config.ts and calls setupNodeEvents. In it, on('task', { ... }) registers named functions. The call cy.task('name', arg) serialises the argument, sends it to Node, runs the function and returns the result into the test. The isolation is deliberate: test code gets no access to the machine, and everything that needs Node goes through explicitly named tasks.

The bridge between the test and Node

Browsercy.task('db:query')Nodeon('task', {…})argresultJSON data only: no functions or DOM elements.
Figure 1. The argument and result travel as serialised data, so you can pass numbers, strings, objects and arrays.

Example: checking state in the database. Before: the test only looks at the text "Paid" in the interface. If the UI updated optimistically and the database write did not happen, the test passes. This assumes a PostgreSQL database with an orders table and a row id = 1042.

// 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 'db:orderStatus'(id: number) {
          const res = await pool.query('SELECT status FROM orders WHERE id = $1', [id]);
          return res.rows[0]?.status ?? null;
        },
        async 'db:reset'() {
          await pool.query('TRUNCATE orders RESTART IDENTITY CASCADE');
          return null;
        },
      });
    },
  },
});

// the test
before(() => cy.task('db:reset'));
it('payment stores the paid status', () => {
  cy.visit('/orders/1042');
  cy.get('[data-cy=pay]').click();
  cy.get('[data-cy=status]').should('have.text', 'Paid');
  cy.task('db:orderStatus', 1042).should('eq', 'paid');
});

Why this way. A task receives one argument (pass an object for several values) and must return a value, a Promise or null: returning undefined makes Cypress complain that the task returned nothing. SQL with a $1 parameter is safer than gluing a string from the test. The pool is created once per run, not per call. In the sample db:reset is a TRUNCATE: a dangerous command, so DB_URL must point only at a test database. The test checks the final state twice: what the user sees and what is stored.

Limits and alternatives. A task has a time limit: the taskTimeout option, 60 seconds by default, and a single call can pass { timeout } as the third argument. An error thrown in a task fails the command and the test. Changing config at run time is the job of setupNodeEvents: through config and returning config; it is also where you subscribe to events such as before:browser:launch and after:spec. Lighter alternatives: cy.exec runs a shell command, cy.readFile and cy.writeFile work with files, cy.request calls an HTTP API. A task is needed where these do not reach, for instance a database. Playwright has no such layer: the test already runs in Node and imports the database client straight into the test or a fixture.

Common mistakes.

  • A task with no return: Cypress requires a value or null, otherwise the command fails.
  • Importing pg or fs in a spec instead of a task: these modules are not there in the browser.
  • Passing several values to a task as separate arguments: only one reaches it, you need one object.
  • Running db:reset against a shared database: other people’s data disappears.

Check yourself

The task log(message) runs console.log(message) and returns nothing. What happens on cy.task('log', 'hi')?

Answer

The command fails with an error that the task returned no value. Add return null.

Why can cy.task('db:orderStatus', 1042) be chained straight into .should('eq', 'paid')?

Answer

Because cy.task is an ordinary command: it yields the task result as the subject for the following steps. But should does not rerun the task itself, it only asserts the value received, so if the database write has not landed yet, you need retries another way.

In an interview. Junior: A test runs in the browser, so I reach the database or files through cy.task: I register a task in setupNodeEvents, it runs in Node and returns the result. A task must return something, at least null. Middle/Senior: I understand the two Cypress processes and that only serialised data crosses the bridge. I keep tasks narrow, with parameterised SQL and a pool, and tie dangerous ones like reset to the test database. For files and HTTP I use exec, readFile and request, and Playwright needs no bridge.

More articles in this chapter