Bird
0
0

Which task definition correctly reads a JSON file and returns the parsed object in cypress.config.js?

hard📝 Application Q8 of 15
Cypress - Plugins and Ecosystem
Which task definition correctly reads a JSON file and returns the parsed object in cypress.config.js?
A<pre>tasks: { readJson({filePath}) { const fs = require('fs') const data = fs.readFileSync(filePath, 'utf8') return JSON.parse(data) } }</pre>
B<pre>tasks: { readJson(filePath) { const fs = require('fs') return fs.readFileSync(filePath) } }</pre>
C<pre>tasks: { readJson(filePath) { const fs = require('fs') return JSON.parse(fs.readFileSync(filePath, 'utf8')) } }</pre>
D<pre>tasks: { readJson(filePath) { const fs = require('fs') return JSON.parse(fs.readFileSync(filePath)) } }</pre>
Step-by-Step Solution
Solution:
  1. Step 1: Understand file reading and JSON parsing

    To parse JSON, the file content must be read as a UTF-8 string before parsing.
  2. Step 2: Analyze options

    tasks: {
      readJson({filePath}) {
        const fs = require('fs')
        const data = fs.readFileSync(filePath, 'utf8')
        return JSON.parse(data)
      }
    }
    uses an object argument and parses correctly but is valid style-wise; however, the question asks for the correct definition, and
    tasks: {
      readJson(filePath) {
        const fs = require('fs')
        return JSON.parse(fs.readFileSync(filePath, 'utf8'))
      }
    }
    is more standard with a single argument.
    tasks: {
      readJson(filePath) {
        const fs = require('fs')
        return fs.readFileSync(filePath)
      }
    }
    returns raw buffer without parsing.
    tasks: {
      readJson(filePath) {
        const fs = require('fs')
        return JSON.parse(fs.readFileSync(filePath))
      }
    }
    misses the encoding argument, so readFileSync returns a buffer, causing JSON.parse to fail.
    tasks: {
      readJson(filePath) {
        const fs = require('fs')
        return JSON.parse(fs.readFileSync(filePath, 'utf8'))
      }
    }
    correctly reads the file as UTF-8 string and parses it.
  3. Final Answer:

    tasks: {
      readJson(filePath) {
        const fs = require('fs')
        return JSON.parse(fs.readFileSync(filePath, 'utf8'))
      }
    }
    is the correct task definition.
  4. Quick Check:

    Always specify 'utf8' when reading JSON files [OK]
Quick Trick: Use 'utf8' encoding before JSON.parse [OK]
Common Mistakes:
  • Omitting 'utf8' encoding causing buffer parse errors
  • Returning raw file content without parsing
  • Incorrect argument destructuring in task

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Cypress Quizzes