Node.js prerequisite in Cypress - Build an Automation Script
/// <reference types="cypress" /> // cypress/plugins/index.js module.exports = (on, config) => { on('task', { getNodeVersion() { const { exec } = require('child_process'); return new Promise((resolve, reject) => { exec('node -v', (error, stdout, stderr) => { if (error) { return reject(error); } resolve(stdout.trim()); }); }); } }); }; // cypress/e2e/node_version_spec.cy.js describe('Node.js Prerequisite Check', () => { it('should confirm Node.js is installed and version is displayed', () => { cy.task('getNodeVersion').then((version) => { expect(version).to.match(/^v\d+\.\d+\.\d+$/); }); }); });
This Cypress test uses a task to run the node -v command in the system shell. The task is defined in cypress/plugins/index.js to execute the command asynchronously and return the trimmed output.
In the test file node_version_spec.cy.js, the test calls cy.task('getNodeVersion') to get the Node.js version string. It then asserts that the output matches the pattern vX.Y.Z where X, Y, and Z are numbers, confirming Node.js is installed and accessible.
This approach follows best practices by separating CLI command execution into a task, handling asynchronous code with promises, and using a clear regular expression assertion.
Now add data-driven testing to check multiple Node.js commands like 'node -v', 'npm -v', and 'npx -v' for their version outputs.