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

Cypress › Extra questions from common lists

How does cy.exec differ from cy.task?

cy.exec ran a shell command and cy.task calls a Node function from setupNodeEvents, but Cypress 16 removed cy.exec in favour of cy.task. A task returns its result to the test, takes one serialised argument and must not return undefined, so null means nothing. Shell commands now run inside a task through execFileSync with an argument array, which bypasses the shell, and calling cy.exec throws.

Cypress · Practice and details

A script must seed the database before a test. cy.exec or cy.task, and what changed in Cypress 16?

The test needs a database with known data, and the project already has a seed script. Browser test code cannot start a process or talk to Postgres: everything outside the browser runs in the Cypress Node process. Two commands existed for this, cy.exec and cy.task.

Important: in Cypress 16 cy.exec() was removed and calling it throws. Shell commands are now run inside cy.task() through child_process.execFileSync() with an argument array: the cy.task docs recommend this because an argument array avoids the shell, so quoting and PATH lookup behave the same on every platform. The comparison with cy.exec remains in interview questions and in older projects.

How it works and why

Both commands step out of the browser into Node. cy.exec('command') ran a shell command and yielded { exitCode, stdout, stderr } (named code before Cypress 15); a non-zero exit code failed the test by default (failOnNonZeroExit: false turned that off). cy.task('name', arg) calls a Node function registered in setupNodeEvents: it receives one serialisable argument, returns a value (or a promise) and must not return undefined, or the command fails; to return «nothing», return null.

cy.exec and cy.task

cy.exec (≤ 15)

shell command

A ready script or CLI. Yields code, stdout, stderr. Removed in Cypress 16.

cy.task

Node function

Your own logic: a DB query, files, data generation. Returns a value to the test. Works in 16 too.

Figure 1. After exec was removed its role is played by task with execFileSync.

Example: before → after

// before (up to 15): a shell command in the test
cy.exec('node scripts/seed.js').its('exitCode').should('eq', 0);
// cypress.config.ts
import { defineConfig } from 'cypress';
import { execFileSync } from 'node:child_process';

export default defineConfig({
  e2e: {
    setupNodeEvents(on) {
      on('task', {
        seedDb() {
          // argument array: no shell
          execFileSync('node', ['scripts/seed.js'], { stdio: 'pipe' });
          return null; // a task cannot return undefined
        },
      });
    },
  },
});

// in the test
cy.task('seedDb');

Note node scripts/seed.js instead of npm run db:seed: on Windows npm is npm.cmd, and execFileSync cannot launch .cmd files without a shell, so running node directly is safer for scripts. If the function needs data, pass it as the second argument cy.task('name', arg) and read the result like any other subject.

A task can be asynchronous and return data to the test: there is one argument, so several values go in an object that the task destructures.

// cypress.config.ts
on('task', {
  async findOrders({ userId, status }: { userId: number; status: string }) {
    const rows = await db.query('select * from orders where user_id = $1 and status = $2', [userId, status]);
    return rows; // a serialised array reaches the test
  },
});

// in the test; { timeout } raises the limit of this command only
cy.task('findOrders', { userId: 7, status: 'paid' }, { timeout: 120000 }).should('have.length', 2);

Limits and alternatives

  • Tasks run in a Node process with the rights of the user who started Cypress: never pass unchecked input from a test to execFileSync.
  • There is a default timeout (taskTimeout, 60 s); long operations are better moved to before:run or a separate CI step.
  • Resetting data is often faster and cleaner through the application API (cy.request) than through a shell.
  • Playwright needs no analogue: the test already runs in Node, so child_process or a DB client is called directly.

Common mistakes

  • A task with no return: Cypress complains that it returned nothing. Return null.
  • Building a shell string from test data: injection risk and OS differences. An argument array solves both.
  • Pulling heavy dependencies into setupNodeEvents at top level: they load at every config start.

Check yourself

A test calls cy.task('seedDb') and the function returns nothing. What happens and how do you fix it?

Answer

Cypress throws an error that the task returned undefined. Fix: return null (or return a useful value).

Why does a task run execFileSync('node', ['scripts/seed.js']) and not a command string?

Answer

An argument array does not go through a shell: no quote parsing, no injection, no differences between OS shells.

In an interview. Junior: Both commands run code outside the browser, in Node. cy.task calls a Node function from the config and returns data to the test, for example a database query. Middle/Senior: In Cypress 16 cy.exec was removed, so I run shell commands from cy.task through execFileSync with an argument array. A task must not return undefined, and for data I prefer the application API.

More articles in this chapter