0
0
Cypresstesting~15 mins

Cypress CLI execution - Build an Automation Script

Choose your learning style9 modes available
Run Cypress tests using CLI and verify test results
Preconditions (2)
Step 1: Open terminal or command prompt
Step 2: Navigate to the project root folder where Cypress is installed
Step 3: Run the command 'npx cypress run' to execute all tests
Step 4: Observe the terminal output for test execution progress
Step 5: Verify that the test run completes without errors
Step 6: Check the summary in the terminal showing number of tests passed and failed
✅ Expected Result: All Cypress tests run successfully via CLI with a summary showing zero failed tests
Automation Requirements - Cypress
Assertions Needed:
Verify CLI command 'npx cypress run' executes without errors
Verify test summary shows zero failed tests
Best Practices:
Use npm scripts to run Cypress CLI commands
Capture and parse CLI output to assert test results
Run tests in headless mode for CI environments
Automated Solution
Cypress
const { exec } = require('child_process');

describe('Cypress CLI execution test', () => {
  it('should run Cypress tests via CLI and verify no failures', (done) => {
    exec('npx cypress run', (error, stdout, stderr) => {
      if (error) {
        done(error);
        return;
      }

      // Check that output contains 'All specs passed!'
      const allPassed = stdout.includes('All specs passed!') || /\d+ passing/.test(stdout);
      expect(allPassed).to.be.true;

      // Check no failures reported
      const failures = /\d+ failing/.exec(stdout);
      expect(failures).to.be.null;

      done();
    });
  });
});

This test uses Node.js exec to run the Cypress CLI command npx cypress run.

It captures the command output and checks for the text indicating all tests passed and no failures.

Assertions verify the CLI run was successful and no tests failed.

Using done callback ensures the test waits for the CLI command to finish before asserting.

Common Mistakes - 3 Pitfalls
Not waiting for the CLI command to finish before asserting
Hardcoding test output strings that may change
{'mistake': 'Running Cypress GUI instead of headless CLI in automation', 'why_bad': 'GUI requires manual interaction and is not suitable for automated CI runs', 'correct_approach': "Use headless CLI mode with 'npx cypress run' for automation"}
Bonus Challenge

Now add data-driven testing by running Cypress CLI with different environment variables and verify tests pass for each

Show Hint