‘process.argv’/’process.argv.slice(1)’ is not working in cypress

I am using cypress with js for the automation testing.
My current requirement is to store the command which user pass to run a script.
Let me explain it in detail:
Here is my package.json file:

"scripts": {
    "e2e-headless": "cypress run --spec cypress/integration/examples/allSpec.js --browser chrome",
    "e2e": "cypress run --spec cypress/integration/examples/allSpec.js --browser chrome --headed",
    "suite": "cypress run --spec cypress/integration/examples/Suite.js --browser chrome --headed"
  },

User can use any script to run. if user run npm run suite command. I want to store this command in a variable. i.e. If I store it in cmd variable and print it, it should give me an output npm run suite

For that I tried below code in test.js file:

const scriptName = process.argv.slice(1); //with different number in argument
console.log('The script name is:' + scriptName);

and

const scriptName = process.argv; //also tried process.argv[2]
console.log('The script name is:' + scriptName);

But it’s not giving me the expected output.
I also tried:

"scripts": {
  "suite": "cross-env MY_SCRIPT_NAME=cypress run --spec cypress/integration/examples/Suite.js --browser chrome --headed"
}
const scriptName = process.env.MY_SCRIPT_NAME;
console.log('The script name is: ' + scriptName);

npm install --save-dev cross-env
But it gives me an error while executing a script that command is not recogised. I can’t put the screenshot of that right now, because I restore my code as it was and don’t want to disturb it.
Please help me. Thank you!

  • 1

    Well what is it giving you? What does the complete process.argv contain?

    – 

  • It’s contains nothing @Pointy

    – 

One way is to add a different flag to each CLI script, see Option #4: –env

"scripts": {
  "e2e-headless": "cypress run --spec ... --browser chrome --env cli=e2e-headless",
  "e2e": "cypress run --spec ... --browser chrome --headed --env cli=e2e",
  "suite": "cypress run --spec ... --browser chrome --headed --env cli=suite"
}

then test.js

const scriptName = Cypress.env('cli')

Leave a Comment