skip to Main Content

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!

2

Answers


  1. 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')
    
    Login or Signup to reply.
  2. If you want the actual text of the script that runs, just read it from package.json, something like

    const scriptName = Cypress.env('cli')
    cy.readFile('package.json')
      .its(`scripts.${scriptName}`)
      .then(cliCommand => {
        console.log(cliCommand)
      })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search