0
0
Cypresstesting~7 mins

Custom plugin development in Cypress

Choose your learning style9 modes available
Introduction

Custom plugins let you add new features to Cypress tests easily. They help you reuse code and make tests simpler.

You want to add a new command to Cypress that you use often.
You need to handle special setup or cleanup before or after tests.
You want to connect Cypress with other tools or APIs.
You want to share common test logic across many test files.
You want to customize how Cypress behaves for your project.
Syntax
Cypress
module.exports = (on, config) => {
  // register event listeners or tasks here
  on('task', {
    myTask(arg) {
      // do something with arg
      return null;
    }
  });
  // return updated config if needed
  return config;
}

on lets you listen to Cypress events or define tasks.

config holds Cypress settings you can change.

Examples
This plugin adds a task named log that prints messages to the console.
Cypress
module.exports = (on, config) => {
  on('task', {
    log(message) {
      console.log(message);
      return null;
    }
  });
}
This plugin changes Chrome browser launch options to disable GPU.
Cypress
module.exports = (on, config) => {
  on('before:browser:launch', (browser = {}, launchOptions) => {
    if (browser.name === 'chrome') {
      launchOptions.args.push('--disable-gpu');
    }
    return launchOptions;
  });
}
Sample Program

This example shows a plugin that adds a greet task. The test calls this task with 'Alice' and checks the returned message.

Cypress
// cypress/plugins/index.js
module.exports = (on, config) => {
  on('task', {
    greet(name) {
      console.log(`Hello, ${name}!`);
      return `Greeted ${name}`;
    }
  });
};

// cypress/e2e/sample.cy.js
describe('Custom Plugin Test', () => {
  it('uses greet task', () => {
    cy.task('greet', 'Alice').then((result) => {
      expect(result).to.equal('Greeted Alice');
    });
  });
});
OutputSuccess
Important Notes

Always return a value or null from tasks to avoid hanging tests.

Use tasks for code that runs in Node.js, not in the browser.

Keep plugins simple and focused on reusable logic.

Summary

Custom plugins add new commands or tasks to Cypress.

They help share code and customize test behavior.

Plugins run in the Node.js environment, separate from browser tests.