0
0
Cypresstesting~5 mins

Task command for Node operations in Cypress - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the task command in Cypress?
The task command lets Cypress run Node.js code outside the browser, enabling operations like file system access or database queries that the browser cannot perform.
Click to reveal answer
intermediate
How do you define a custom task in Cypress?
You define a custom task inside the cypress.config.js file under the setupNodeEvents function using on('task', { ... }) and provide task names with their corresponding Node.js functions.
Click to reveal answer
intermediate
Example: What does this Cypress task do?<br>
on('task', { readFile(filename) { return fs.readFileSync(filename, 'utf8') } })
This task reads the content of a file named filename synchronously and returns its text content to the Cypress test.
Click to reveal answer
beginner
Why can't Cypress tests directly use Node.js modules like fs inside cy.* commands?
Because Cypress commands run inside the browser environment, which does not have access to Node.js modules. The task command bridges this gap by running Node code in the background process.
Click to reveal answer
beginner
How do you call a custom task named readFile from a Cypress test?
Use cy.task('readFile', 'path/to/file.txt').then(content => { ... }) to call the task and handle the returned content asynchronously.
Click to reveal answer
What is the main reason to use cy.task in Cypress?
ATo run Node.js code like file operations
BTo interact with DOM elements
CTo send HTTP requests
DTo take screenshots
Where do you define custom tasks in a Cypress project?
AIn <code>cypress.config.js</code> under <code>setupNodeEvents</code>
BIn <code>package.json</code>
CIn the browser console
DInside the test spec files
Which of these is a valid way to call a task named getData in a Cypress test?
Acy.getData()
Bcy.invoke('getData')
Ccy.task('getData')
Dcy.run('getData')
What kind of code runs inside the task handler in Cypress?
ABrowser JavaScript
BNode.js code
CCSS styles
DHTML markup
If a task returns a value, how do you access it in your Cypress test?
ADirectly as a return value
BUsing a callback function
CIt is not possible to get return values
DUsing a <code>.then()</code> after <code>cy.task()</code>
Explain how Cypress task commands help in performing Node.js operations during tests.
Think about what Cypress cannot do inside the browser and how tasks solve that.
You got /4 concepts.
    Describe the steps to create and use a custom task that reads a file content in Cypress.
    Focus on where to write the task and how to call it from the test.
    You got /4 concepts.