Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to define a Cypress task that returns the current working directory.
Cypress
Cypress.Commands.add('getCwd', () => { return cy.task([1]) });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using an incorrect task name that is not registered in plugins.
Forgetting to wrap the task name in quotes.
✗ Incorrect
The task name 'cwd' is commonly used to get the current working directory in Cypress tasks.
2fill in blank
mediumComplete the code to register a Cypress task that reads a file asynchronously.
Cypress
module.exports = (on, config) => {
on('task', {
readFile([1]) {
const fs = require('fs').promises;
return fs.readFile(path, 'utf8');
}
});
}; Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a parameter name different from the variable used inside the function.
Not using async/await or promises for reading files.
✗ Incorrect
The parameter name 'path' matches the variable used inside the function to read the file.
3fill in blank
hardFix the error in the Cypress task that writes data to a file.
Cypress
on('task', { writeFile([1]) { const fs = require('fs'); return fs.writeFileSync(filePath, data); } });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing parameters without destructuring causing undefined variables.
Using writeFileSync without proper parameters.
✗ Incorrect
The function parameter should destructure an object with filePath and data to use both variables inside the function.
4fill in blank
hardFill both blanks to create a Cypress task that deletes a file and returns success status.
Cypress
on('task', { deleteFile([1]) { const fs = require('fs'); try { fs.unlinkSync([2]); return true; } catch (err) { return false; } } });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names causing runtime errors.
Not handling exceptions properly.
✗ Incorrect
The parameter and the argument to unlinkSync must be the same variable 'filePath' to delete the correct file.
5fill in blank
hardFill all three blanks to define a Cypress task that lists files in a directory and filters by extension.
Cypress
on('task', { listFiles([1]) { const fs = require('fs'); const files = fs.readdirSync([2]); return files.filter(file => file.endsWith([3])); } });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names causing errors.
Not filtering files correctly by extension.
✗ Incorrect
The parameter and argument for readdirSync should be 'dirPath', and the filter uses 'ext' to check file extensions.