Task command for Node operations in Cypress - Build an Automation Script
/// <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.
Now add data-driven testing to read three different files ('sample1.txt', 'sample2.txt', 'sample3.txt') and verify their contents using the same task command.
Practice
cy.task() command in Cypress?Solution
Step 1: Understand the role of
Thecy.task()cy.task()command allows Cypress tests to execute Node.js code outside the browser environment.Step 2: Differentiate from other commands
Commands like selecting elements or assertions happen inside the browser, butcy.task()runs backend code for tasks like file access.Final Answer:
To run Node.js code during Cypress tests -> Option AQuick Check:
Node code execution = A [OK]
cy.task() runs backend Node code [OK]- Confusing
cy.task()with DOM commands - Thinking
cy.task()runs in the browser - Assuming
cy.task()is for assertions
readFile in a Cypress test?Solution
Step 1: Recall the syntax for calling tasks
In Cypress, tasks defined in the config are called usingcy.task('taskName').Step 2: Verify other options
cy.readFileis a different command for reading files in the browser context, not tasks. The others are invalid commands.Final Answer:
cy.task('readFile') -> Option CQuick Check:
Usecy.task()to call tasks [OK]
cy.task('name') to run tasks [OK]- Using
cy.readFileinstead ofcy.task - Trying non-existent commands like
cy.nodeTask - Passing task name without quotes
cypress.config.js:
tasks: {
getEnv() {
return process.env.NODE_ENV
}
}
What will this test print?
cy.task('getEnv').then(env => {
cy.log(env)
})Solution
Step 1: Understand the task function
The taskgetEnvreturns the value ofprocess.env.NODE_ENV, which is the environment mode (like 'development' or 'production').Step 2: Analyze the test code
The test callscy.task('getEnv')and logs the returned value, so it will print the current environment string.Final Answer:
It logs the current NODE_ENV value -> Option DQuick Check:
Task returns env string = B [OK]
cy.task() logs them [OK]- Assuming task runs in browser context
- Expecting syntax errors from valid code
- Thinking environment variables are empty by default
cypress.config.js?
tasks: {
readFile(path) {
const fs = require('fs')
return fs.readFileSync(path, 'utf8')
}
}
When called as cy.task('readFile', 'data.txt'), it throws an error.Solution
Step 1: Understand task function requirements
Cypress tasks should return a value or a Promise. Using synchronousreadFileSyncis allowed but can cause blocking issues.Step 2: Identify best practice for async operations
To avoid errors and improve performance, tasks reading files should be async and return a Promise, e.g., usingfs.promises.readFile.Step 3: Analyze the error cause
The error likely occurs because Cypress expects a Promise for async tasks, so defining the task as async fixes it.Final Answer:
The task should be defined as an async function returning a Promise -> Option BQuick Check:
Async tasks return Promises = D [OK]
- Thinking synchronous code always works in tasks
- Believing
requireis disallowed inside tasks - Assuming tasks cannot take arguments
Solution
Step 1: Read file asynchronously and parse JSON
async readKeys(file) { const fs = require('fs').promises const data = await fs.readFile(file, 'utf8') return Object.keys(JSON.parse(data)) } correctly usesfs.promises.readFilewithawaitto read the file asynchronously, then parses JSON.Step 2: Extract keys from parsed object
It returnsObject.keys()of the parsed JSON, which gives the top-level keys as required.Step 3: Identify errors in other options
readKeys(file) { const fs = require('fs') const data = fs.readFileSync(file, 'utf8') return JSON.parse(data).keys() } incorrectly calls.keys()on the parsed object (should useObject.keys()). Options C and D try to get keys from raw string data, which is incorrect.Final Answer:
async readKeys(file) { const fs = require('fs').promises const data = await fs.readFile(file, 'utf8') return Object.keys(JSON.parse(data)) } -> Option AQuick Check:
Async read + JSON parse + Object.keys = A [OK]
- Calling .keys() on object instead of Object.keys()
- Trying to get keys from raw string data
- Using synchronous read without async/await properly
Ready to prove it?
Pass the test and this pattern moves unknown
