In Cypress, tasks are useful for executing Node.js code as part of Cypress test scripts. They allow us to perform operations such as logging messages, reading and writing files, and interacting with databases.
Once a task is registered, we can invoke it from a Cypress test using the cy.task(taskName) command, passing any required arguments.
Starting with Cypress 10, tasks are configured in the setupNodeEvents() function within the cypress.config.js file. In earlier versions (Cypress 9 and below), they were typically configured in the cypress/plugins/index.js file.
If we want to display log messages in the CLI (Command-Line Interface), using cy.log() is not sufficient because it displays messages in the Cypress Test Runner rather than the terminal.
To display messages in the terminal, we can create a custom task using the on('task', {...}) event handler inside the setupNodeEvents() function in cypress.config.js. We can then invoke the task from our Cypress test script using cy.task().
Below is an example of defining a custom Cypress task in cypress.config.js and calling it from a test script.
Configure the Task Example script:
Create or update the cypress.config.js file to register a custom task using the on('task', {...}) event handler inside the setupNodeEvents() function.
const { defineConfig } = require(“cypress”);
module.exports = defineConfig({
e2e: {
async setupNodeEvents(on, config) {
on(‘task’,{
log(message){
console.log(message);
return null;
}
})
return config;
},
},
});
Explanation:
setupNodeEvents(on, config): Configures Node.js event handlers for Cypress.on('task', {...}): Registers custom tasks that can be executed from Cypress tests.log(message): Defines a custom task namedlogthat accepts a message as an argument.console.log(message): Prints the message in the terminal where Cypress is running.return null: Indicates that the task completed successfully without returning a meaningful result.return config: Returns the Cypress configuration object.
Calling a Task in a Cypress Test Script
We can execute a custom task using the cy.task() command by passing the task name and the required argument.
The following example demonstrates how to call the log task that we defined in the previous example and display a message in the CLI (Command-Line Interface).
Example:
cy.task('log', 'Hello');
Explanation:
cy.task(): Executes a registered custom task.'log': Specifies the name of the task registered incypress.config.js.'Hello': Passes the message as an argument to the task.
Output: The message Hello is printed in the terminal where Cypress is running.