0
0
Cypresstesting~10 mins

Task command for Node operations in Cypress - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test uses Cypress task command to perform a Node.js operation that reads a file's content. It verifies that the content returned by the task matches the expected text.

Test Code - Cypress
Cypress
/// <reference types="cypress" />

// In cypress/plugins/index.js or cypress.config.js
module.exports = (on, config) => {
  on('task', {
    readFileContent(filename) {
      const fs = require('fs')
      return fs.readFileSync(filename, 'utf8')
    }
  })
}

// In the test file
describe('Task command for Node operations', () => {
  it('reads file content using task command', () => {
    const testFile = 'cypress/fixtures/sample.txt'
    cy.task('readFileContent', testFile).then((content) => {
      expect(content).to.contain('Hello Cypress')
    })
  })
})
Execution Trace - 7 Steps
StepActionSystem StateAssertionResult
1Test startsCypress test runner initialized-PASS
2Cypress opens browser and loads test pageBrowser opened with Cypress test environment-PASS
3Test calls cy.task('readFileContent', 'cypress/fixtures/sample.txt')Cypress sends task request to Node process-PASS
4Node process executes task: reads file content synchronouslyFile 'sample.txt' content read: 'Hello Cypress! This is a sample file.'-PASS
5Task returns file content to Cypress testCypress receives file content string-PASS
6Test asserts content includes 'Hello Cypress'Content string contains expected textexpect(content).to.contain('Hello Cypress')PASS
7Test ends successfullyTest passed, no errors-PASS
Failure Scenario
Failing Condition: The file 'cypress/fixtures/sample.txt' does not exist or path is incorrect
Execution Trace Quiz - 3 Questions
Test your understanding
What does the cy.task command do in this test?
AClicks a button on the webpage
BNavigates to a new URL
CRuns a Node.js function to read a file and returns its content
DTypes text into an input field
Key Result
Using Cypress task commands allows running Node.js code during tests, enabling operations like file reading that are not possible in the browser context.