0
0
Cypresstesting~15 mins

Custom plugin development in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify custom Cypress plugin that logs a message
Preconditions (2)
Step 1: Open cypress/plugins/index.js
Step 2: Add a custom task named 'logMessage' that logs a message to the console
Step 3: In a test file, call cy.task('logMessage', 'Hello from plugin')
Step 4: Run the test suite
✅ Expected Result: The console shows the message 'Hello from plugin' logged by the custom plugin task
Automation Requirements - Cypress
Assertions Needed:
Verify the custom task 'logMessage' is called
Verify the message passed to the task is logged in the console
Best Practices:
Use Cypress task API for plugin communication
Keep plugin code in cypress/plugins/index.js
Use proper logging and error handling in plugin
Write clear and maintainable test code
Automated Solution
Cypress
/// <reference types="cypress" />

// cypress/plugins/index.js
module.exports = (on, config) => {
  on('task', {
    logMessage(message) {
      console.log(message)
      return null
    }
  })
}

// cypress/e2e/plugin_test.cy.js
describe('Custom plugin task test', () => {
  it('should log message via custom plugin task', () => {
    cy.task('logMessage', 'Hello from plugin')
  })
})

The cypress/plugins/index.js file defines a custom task named logMessage. This task receives a message and logs it to the Node.js console. Returning null indicates no value is returned to the test.

The test file plugin_test.cy.js calls cy.task('logMessage', 'Hello from plugin') to invoke the plugin task. When the test runs, the message appears in the terminal console where Cypress runs.

This setup uses Cypress's plugin system correctly, separating plugin code from test code, and uses the task API to communicate between the browser and Node environment.

Common Mistakes - 3 Pitfalls
Defining the plugin task inside the test file instead of cypress/plugins/index.js
Not returning null or a value from the task function
Using console.log inside the test instead of the plugin task
Bonus Challenge

Now add a custom plugin task that returns the current date and time, and write a test to verify it returns a valid date string.

Show Hint