Creating Custom Cypress Plugins
π ️ How to Create Custom Cypress Plugins
π 1. Locate the Cypress Plugin File
Cypress plugins are defined in:
arduino
Copy
Edit
cypress/plugins/index.js (or cypress.config.js in Cypress 10+)
This is where you write custom plugin logic that runs in the Node.js process, separate from your browser-based tests.
⚙️ 2. Basic Plugin Structure (Cypress < v10)
In older Cypress versions:
js
Copy
Edit
// cypress/plugins/index.js
module.exports = (on, config) => {
on('task', {
logMessage(message) {
console.log('PLUGIN LOG:', message)
return null
},
async getData() {
// Example: simulate async operation
return new Promise((resolve) => {
setTimeout(() => resolve('Fetched data'), 1000)
});
}
});
return config;
};
Now in your test file, you can call this plugin task:
js
Copy
Edit
cy.task('logMessage', 'Hello from test!');
cy.task('getData').then((data) => {
expect(data).to.equal('Fetched data');
});
π§± 3. Advanced Use Cases
Database access (using Node.js libraries like pg, mysql)
File system operations (fs module)
API stubbing or mocking responses
Environment-specific config overrides
Email or 2FA code fetching (from external services)
π¦ 4. Creating a Reusable Plugin Module
Instead of adding everything to index.js, modularize your plugin:
js
Copy
Edit
// cypress/plugins/custom-logger.js
module.exports = (on) => {
on('task', {
logMessage(message) {
console.log(`[LOG]: ${message}`);
return null;
}
});
};
And in your index.js:
js
Copy
Edit
const customLogger = require('./custom-logger');
module.exports = (on, config) => {
customLogger(on);
return config;
};
π 5. For Cypress v10+ and the New cypress.config.js
Plugins have been renamed to "Node events setup":
js
Copy
Edit
// cypress.config.js (Cypress v10+)
import { defineConfig } from 'cypress';
export default defineConfig({
e2e: {
setupNodeEvents(on, config) {
on('task', {
log: (msg) => {
console.log(`[LOG]: ${msg}`);
return null;
}
});
return config;
},
},
});
π§ͺ 6. Best Practices
Keep plugins small and modular
Use async/await for cleaner async operations
Avoid side effects unless intentional (e.g., modifying files or DB)
Log clearly to differentiate plugin vs. test output
π Need Ideas?
You could create plugins for:
Injecting test data into a database before each run
Generating PDFs or screenshots after tests
Accessing APIs not exposed to the browser
Pulling OTP codes from email or SMS gateways during login tests
Learn Testing Tools Training in Hyderabad
Read More
How to Choose the Right Testing Tool for Your Project
Data-Driven Testing in Selenium
π Advanced Usage in Testing
Visit Our IHUB Talent Training Institute in Hyderabad
Comments
Post a Comment