0
0
Cypresstesting~5 mins

Task command for Node operations in Cypress

Choose your learning style9 modes available
Introduction

Sometimes, you need to run Node.js code inside your Cypress tests. The task command lets you do that safely.

You want to read or write files during a test.
You need to run a script or command that only Node.js can do.
You want to get data from the system or environment variables.
You want to perform setup or cleanup tasks outside the browser.
You want to reuse existing Node.js code inside your test.
Syntax
Cypress
In cypress.config.js or plugins file:

on('task', {
  taskName(args) {
    // Node.js code here
    return result;
  }
});

In test file:

cy.task('taskName', args).then((result) => {
  // use result in test
});

The task runs in the Node.js environment, not the browser.

Always return a value or a promise from the task function.

Examples
This example logs a message to the Node.js console during the test.
Cypress
on('task', {
  log(message) {
    console.log(message);
    return null;
  }
});

cy.task('log', 'Hello from Cypress');
This example reads a file content using Node.js and checks it in the test.
Cypress
on('task', {
  readFile(filename) {
    const fs = require('fs');
    return fs.readFileSync(filename, 'utf8');
  }
});

cy.task('readFile', 'data.txt').then((content) => {
  expect(content).to.include('Hello');
});
Sample Program

This test uses a task to multiply two numbers in Node.js and checks the result in the test.

Cypress
// cypress.config.js
const { defineConfig } = require('cypress');

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('task', {
        multiply({a, b}) {
          return a * b;
        }
      });
    }
  }
});

// test.cy.js

describe('Task command example', () => {
  it('multiplies two numbers using task', () => {
    cy.task('multiply', {a: 5, b: 4}).then((result) => {
      expect(result).to.equal(20);
    });
  });
});
OutputSuccess
Important Notes

Tasks run outside the browser, so they can access the file system and other Node.js features.

Use tasks to keep your tests clean and avoid mixing browser and Node.js code.

Summary

The task command lets Cypress run Node.js code during tests.

Define tasks in the config file and call them in tests with cy.task().

Tasks help with file access, environment info, and complex operations.