Bird
0
0

What is wrong with this task definition in cypress.config.js?

medium📝 Debug Q14 of 15
Cypress - Plugins and Ecosystem
What is wrong with this task definition in 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.
AThe task function must return a Promise or value, but <code>readFileSync</code> is synchronous
BThe task should be defined as an async function returning a Promise
CTasks cannot accept arguments
DThe <code>require</code> statement is not allowed inside tasks
Step-by-Step Solution
Solution:
  1. Step 1: Understand task function requirements

    Cypress tasks should return a value or a Promise. Using synchronous readFileSync is allowed but can cause blocking issues.
  2. 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., using fs.promises.readFile.
  3. 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.
  4. Final Answer:

    The task should be defined as an async function returning a Promise -> Option B
  5. Quick Check:

    Async tasks return Promises = D [OK]
Quick Trick: Use async functions for tasks doing file I/O [OK]
Common Mistakes:
  • Thinking synchronous code always works in tasks
  • Believing require is disallowed inside tasks
  • Assuming tasks cannot take arguments

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Cypress Quizzes