Bird
Raised Fist0
Cypresstesting~20 mins

Task command for Node operations in Cypress - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Node Task Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Cypress task command?
Consider this Cypress task command that reads a file using Node.js fs module. What will be logged in the test runner console?
Cypress
Cypress.Commands.add('readFileTask', (filePath) => {
  return cy.task('readFile', filePath);
});

// In plugins/index.js
module.exports = (on) => {
  const fs = require('fs');
  on('task', {
    readFile(filePath) {
      return fs.readFileSync(filePath, 'utf8');
    }
  });
};

// Test code
cy.readFileTask('cypress/fixtures/sample.txt').then((content) => {
  cy.log(content);
});
ALogs the content of 'sample.txt' as a string in the Cypress test runner
BThrows a syntax error because fs.readFileSync is used incorrectly
CFails with an error because 'task' is not defined in Cypress commands
DLogs an object with file metadata instead of content
Attempts:
2 left
💡 Hint
Remember that Cypress tasks run Node code outside the browser context and can return values to the test.
❓ assertion
intermediate
1:30remaining
Which assertion correctly verifies the result of a Cypress task?
You have a Cypress task that returns the number of files in a directory. Which assertion correctly checks that the count is 5?
Cypress
cy.task('countFiles', 'cypress/fixtures').then((count) => {
  // Which assertion goes here?
});
Aassert.isTrue(count === 5);
Bassert.isFalse(count !== 5);
Cexpect(count).to.equal(5);
Dexpect(count).to.be.greaterThan(5);
Attempts:
2 left
💡 Hint
Use the most direct and readable assertion for equality.
🔧 Debug
advanced
2:30remaining
Why does this Cypress task fail with 'Cannot read property' error?
Given this task code, why does the test fail with "ENOENT: no such file or directory" error?
Cypress
// plugins/index.js
module.exports = (on) => {
  on('task', {
    countFiles(dir) {
      const fs = require('fs');
      const files = fs.readdirSync(dir);
      return files.length;
    }
  });
};

// Test code
cy.task('countFiles', 'cypress/fixtures').then((count) => {
  expect(count).to.be.a('number');
});
AThe directory path passed is incorrect or does not exist, so fs.readdirSync throws an error
BThe 'on' function is not properly imported in plugins file
CThe task function is missing a return statement
DThe test code does not handle the promise returned by cy.task
Attempts:
2 left
💡 Hint
Check if the directory path is valid and accessible by Node.
🧠 Conceptual
advanced
1:30remaining
What is the main benefit of using Cypress task commands for Node operations?
Why should you use Cypress task commands to perform Node.js operations instead of running them directly in test code?
ABecause task commands automatically retry on failure
BBecause task commands run faster than browser code
CBecause Cypress does not support asynchronous code in tests
DBecause Cypress test code runs in the browser and cannot access Node APIs directly
Attempts:
2 left
💡 Hint
Think about the environment where Cypress test code runs versus where Node code runs.
❓ framework
expert
3:00remaining
Which is the correct way to define and use a Cypress task that deletes a file?
You want to create a Cypress task named 'deleteFile' that deletes a file at a given path. Which option correctly defines the task and uses it in a test?
A
// plugins/index.js
module.exports = (on) => {
  const fs = require('fs');
  on('task', {
    deleteFile(filePath) {
      return fs.unlink(filePath);
    }
  });
};

// Test code
cy.task('deleteFile', 'cypress/fixtures/temp.txt').then(() => {
  cy.log('File deleted');
});
B
// plugins/index.js
module.exports = (on) => {
  const fs = require('fs');
  on('task', {
    deleteFile(filePath) {
      fs.unlinkSync(filePath);
      return null;
    }
  });
};

// Test code
cy.task('deleteFile', 'cypress/fixtures/temp.txt').then((result) => {
  expect(result).to.be.null;
});
C
// plugins/index.js
module.exports = (on) => {
  const fs = require('fs');
  on('task', {
    deleteFile(filePath) {
      fs.unlinkSync(filePath);
    }
  });
};

// Test code
cy.task('deleteFile', 'cypress/fixtures/temp.txt').then((res) => {
  expect(res).to.equal('deleted');
});
D
// plugins/index.js
module.exports = (on) => {
  const fs = require('fs');
  on('task', {
    deleteFile(filePath) {
      fs.unlink(filePath, (err) => {
        if (err) throw err;
      });
      return 'done';
    }
  });
};

// Test code
cy.task('deleteFile', 'cypress/fixtures/temp.txt').then((res) => {
  expect(res).to.equal('done');
});
Attempts:
2 left
💡 Hint
Remember that tasks must return a value or null, and asynchronous callbacks must be handled properly.

Practice

(1/5)
1. What is the main purpose of the cy.task() command in Cypress?
easy
A. To run Node.js code during Cypress tests
B. To select elements on the webpage
C. To assert values in the DOM
D. To take screenshots automatically

Solution

  1. Step 1: Understand the role of cy.task()

    The cy.task() command allows Cypress tests to execute Node.js code outside the browser environment.
  2. Step 2: Differentiate from other commands

    Commands like selecting elements or assertions happen inside the browser, but cy.task() runs backend code for tasks like file access.
  3. Final Answer:

    To run Node.js code during Cypress tests -> Option A
  4. Quick Check:

    Node code execution = A [OK]
Hint: Remember: cy.task() runs backend Node code [OK]
Common Mistakes:
  • Confusing cy.task() with DOM commands
  • Thinking cy.task() runs in the browser
  • Assuming cy.task() is for assertions
2. Which of the following is the correct way to call a task named readFile in a Cypress test?
easy
A. cy.command('readFile')
B. cy.readFile('readFile')
C. cy.task('readFile')
D. cy.nodeTask('readFile')

Solution

  1. Step 1: Recall the syntax for calling tasks

    In Cypress, tasks defined in the config are called using cy.task('taskName').
  2. Step 2: Verify other options

    cy.readFile is a different command for reading files in the browser context, not tasks. The others are invalid commands.
  3. Final Answer:

    cy.task('readFile') -> Option C
  4. Quick Check:

    Use cy.task() to call tasks [OK]
Hint: Use cy.task('name') to run tasks [OK]
Common Mistakes:
  • Using cy.readFile instead of cy.task
  • Trying non-existent commands like cy.nodeTask
  • Passing task name without quotes
3. Given this task definition in cypress.config.js:
tasks: {
  getEnv() {
    return process.env.NODE_ENV
  }
}
What will this test print?
cy.task('getEnv').then(env => {
  cy.log(env)
})
medium
A. It throws a syntax error
B. It logs an empty string
C. It logs 'undefined'
D. It logs the current NODE_ENV value

Solution

  1. Step 1: Understand the task function

    The task getEnv returns the value of process.env.NODE_ENV, which is the environment mode (like 'development' or 'production').
  2. Step 2: Analyze the test code

    The test calls cy.task('getEnv') and logs the returned value, so it will print the current environment string.
  3. Final Answer:

    It logs the current NODE_ENV value -> Option D
  4. Quick Check:

    Task returns env string = B [OK]
Hint: Tasks return Node values; cy.task() logs them [OK]
Common Mistakes:
  • Assuming task runs in browser context
  • Expecting syntax errors from valid code
  • Thinking environment variables are empty by default
4. 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.
medium
A. The task function must return a Promise or value, but readFileSync is synchronous
B. The task should be defined as an async function returning a Promise
C. Tasks cannot accept arguments
D. The require statement is not allowed inside tasks

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]
Hint: 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
5. You want to create a Cypress task that reads a JSON file and returns only the keys of the top-level object. Which task definition is correct?
hard
A. async readKeys(file) { const fs = require('fs').promises const data = await fs.readFile(file, 'utf8') return Object.keys(JSON.parse(data)) }
B. readKeys(file) { const fs = require('fs') const data = fs.readFileSync(file, 'utf8') return JSON.parse(data).keys() }
C. async readKeys(file) { const fs = require('fs') const data = await fs.readFile(file, 'utf8') return Object.keys(data) }
D. readKeys(file) { const fs = require('fs') const data = fs.readFileSync(file, 'utf8') return Object.keys(data) }

Solution

  1. Step 1: Read file asynchronously and parse JSON

    async readKeys(file) { const fs = require('fs').promises const data = await fs.readFile(file, 'utf8') return Object.keys(JSON.parse(data)) } correctly uses fs.promises.readFile with await to read the file asynchronously, then parses JSON.
  2. Step 2: Extract keys from parsed object

    It returns Object.keys() of the parsed JSON, which gives the top-level keys as required.
  3. Step 3: Identify errors in other options

    readKeys(file) { const fs = require('fs') const data = fs.readFileSync(file, 'utf8') return JSON.parse(data).keys() } incorrectly calls .keys() on the parsed object (should use Object.keys()). Options C and D try to get keys from raw string data, which is incorrect.
  4. Final Answer:

    async readKeys(file) { const fs = require('fs').promises const data = await fs.readFile(file, 'utf8') return Object.keys(JSON.parse(data)) } -> Option A
  5. Quick Check:

    Async read + JSON parse + Object.keys = A [OK]
Hint: Parse JSON first, then get keys with Object.keys() [OK]
Common Mistakes:
  • Calling .keys() on object instead of Object.keys()
  • Trying to get keys from raw string data
  • Using synchronous read without async/await properly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard