How to allow user to enter value in shell script for package.json scripts

24 Views Asked by At

I am using Percy and Cypress to run visual tests on my Nextjs app.

To run a single spec I add this to the script of my package.json eg

"scripts": {
  "test-visual:single": "start-server-and-test 'npm run dev' http://localhost:3000 'percy exec -- cypress run --spec /path/to/test.cy.ts'",
},

I want the user to enter the path of the test spec (/path/to/test.cy.ts). What's the right way to do this?

I have tried to use $PATH

$PATH=/path/to/test.cy.ts npm run test-visual:single

"test-visual:single": "start-server-and-test 'npm run dev' http://localhost:3000 'percy exec -- cypress run --spec $PATH'",

I have also tried:

npm run test-visual:single /path/to/test.cy.ts

"scripts": {
  "test-visual:single": "start-server-and-test 'npm run dev' http://localhost:3000 
 'percy exec -- cypress run --spec $1'",
},

with no luck

1

There are 1 best solutions below

0
user1934428 On

You could maintain a template version of your package.json, say package.json.template:

...
"scripts": {
  "test-visual:single": "start-server-and-test 'npm run dev' http://localhost:3000 'percy exec -- cypress run --spec $tpath'",
},
...

Now assume that in the script which uses this json, the user (invoker) puts the path to be used as the first parameter of the script. You can then do a

tpath=$1
export tpath
envsubst '$tpath' <package.json.template >package.json

If you need the path only in this one place, this can be simplified of course to

tpath=$1 envsubst '$tpath' <package.json.template >package.json

And if you are sure that your template file does not contain any other $, which could incorrectly be understood as a variable reference, you can write it even simpler:

tpath=$1 envsubst <package.json.template >package.json