Bird
0
0

You want to implement a plugin task that reads a JSON file asynchronously and returns its parsed content. Which code snippet correctly achieves this?

hard📝 Application Q8 of 15
Cypress - Plugins and Ecosystem
You want to implement a plugin task that reads a JSON file asynchronously and returns its parsed content. Which code snippet correctly achieves this?
A<pre>const fs = require('fs').promises; module.exports = (on) => { on('task', { readJson(path) { fs.readFile(path).then(data => JSON.parse(data)); } }); };</pre>
B<pre>const fs = require('fs'); module.exports = (on) => { on('task', { readJson(path) { const data = fs.readFileSync(path); return JSON.parse(data); } }); };</pre>
C<pre>const fs = require('fs'); module.exports = (on) => { on('task', { readJson(path) { fs.readFile(path, (err, data) => { if (err) throw err; return JSON.parse(data); }); } }); };</pre>
D<pre>const fs = require('fs').promises; module.exports = (on) => { on('task', { readJson(path) { return fs.readFile(path, 'utf8').then(JSON.parse); } }); };</pre>
Step-by-Step Solution
Solution:
  1. Step 1: Identify asynchronous file reading

    Using fs.promises.readFile returns a promise, enabling async handling.
  2. Step 2: Return the promise from the task

    Returning the promise ensures Cypress waits for the task to complete.
  3. Step 3: Parse JSON after reading

    Using .then(JSON.parse) parses the file content correctly.
  4. Final Answer:

    const fs = require('fs').promises;
    module.exports = (on) => {
      on('task', {
        readJson(path) {
          return fs.readFile(path, 'utf8').then(JSON.parse);
        }
      });
    };
    correctly returns a promise resolving to parsed JSON.
  5. Quick Check:

    Return promise to handle async tasks properly [OK]
Quick Trick: Return promises in async plugin tasks [OK]
Common Mistakes:
  • Using callback without returning a promise
  • Not returning anything from the task
  • Using synchronous read without async handling

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Cypress Quizzes