/// <reference types="cypress" />
// cypress/plugins/index.js
const fs = require('fs');
module.exports = (on, config) => {
on('task', {
readFileContent(filename) {
return new Promise((resolve, reject) => {
fs.readFile(`cypress/fixtures/${filename}`, 'utf8', (err, data) => {
if (err) {
return reject(err);
}
resolve(data);
});
});
}
});
};
// cypress/e2e/readFileTask.cy.js
describe('Read file content using Cypress task', () => {
it('should read sample.txt content via task', () => {
cy.task('readFileContent', 'sample.txt').then((content) => {
expect(content).to.equal('Hello Cypress!');
});
});
});The plugins/index.js file defines a Cypress task named readFileContent that uses Node's fs.readFile to read a file asynchronously from the cypress/fixtures folder. It returns a promise that resolves with the file content.
The test file readFileTask.cy.js calls this task with cy.task('readFileContent', 'sample.txt'). The returned content is then asserted to equal the expected string 'Hello Cypress!' using expect.
This approach keeps Node operations separate from browser test code and uses Cypress best practices for asynchronous tasks and assertions.