Back

Technologies:

javascriptjavascript
avatar
Tolerim
a month ago

How can I pass parameters to an npm script when running it through the command line using Cypress?

I'm trying to pass param1 and param2 as parameters when running a script through the command line in test.cy.js. The following code is used:

it('Cleans data', () => {

    const param1 = process.env.npmconfigparam1;
    const param2 = process.env.npmconfigparam2;

    before(function () {
        cy.visit('/')

        //Login
        cy.get('#username').type(param1)
        cy.get('#password').type(param2)
        cy.get('#loginBtn').click()
 })
The script is defined in package.json with the following code:

"my-script": "npx cypress run --spec \"test.cy.js\" --param1 value1 --param2 value2"
When running the command 'npm run my-script -- [email protected] --param2=11111111', I get the error 'error: unknown option: --param1'. Is there a way to pass parameters into the npm script of Cypress?

Answers(2)
avatar
Vogi
a month ago
Verified Answer
Yes, you can pass parameters into the npm script of Cypress. When calling a command using npm run, you need to pass the command's arguments using the -- string. For example, if you have the following command defined in your package.json:
{
  "scripts": {
    "cy:run": "cypress run"
  }
}
You can pass parameters by running the command:
The -- separator is used to separate the params passed to npm command itself and the params passed to your script. I hope this helps! Let me know if you have any other questions.

Sources

Passing arguments to npm script in package.json [duplicate]Sending command line arguments to npm script - Stack OverflowCommand Line | Cypress DocumentationCypress: Passing the param into npm script when run by CL
avatar
Tolerim
a month ago
Yes, you can pass parameters into an npm script when running Cypress. However, the syntax you are using is incorrect. To pass parameters to an npm script, you need to use the format --=. Here's an updated version of your script in package.json, with the correct parameter syntax:
"my-script": "npx cypress run --spec \"test.cy.js\" --env param1=value1,param2=value2"
And to run the script with parameters from the command line, use this command:
npm run my-script -- --env [email protected],param2=11111111
The -- before --env is important because it separates the npm arguments from the arguments being passed to the Cypress command. Then, within your test script, you can access these parameters using Cypress.env('param1') and Cypress.env('param2'), like so:
const param1 = Cypress.env('param1');
const param2 = Cypress.env('param2');
;