Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing custom arguments to jest

Tags:

jestjs

Our client needs to run the entire test battery with a simple command, but he also needs to be able to change environments with a parameter. Currently we run:

jest

And it runs all the files, which is good. We need something like:

 jest --env=local
 jest --env=dev
 jest --env=qa

Is this possible in any way? The test files should be the same, all the testing works the same, we only need to run it on different urls

I've tried to parse the commands on my own, but jest won't let me. If I enter something different than the predefined commands, it fails with:

● Unrecognized CLI Parameter:

  Unrecognized option "a". Did you mean "$0"?

  CLI Options Documentation:
  https://facebook.github.io/jest/docs/en/cli.html

I saw that I can add my own environments. I've tried with:

jest --env=qa

...to see its output and it prints:

● Validation Error:

  Test environment qa cannot be found. Make sure the testEnvironment configuration option points to an existing node module.

  Configuration Documentation:
  https://facebook.github.io/jest/docs/configuration.html

But when I try to change those options I'm really lost. I can't seem to find something easy like

dev = {
    url = 'devUrl';
}
qa = {
    url = 'qaUrl';
}
etc.

Thanks for your time.

like image 255
Mati Berrutti Avatar asked Apr 12 '18 14:04

Mati Berrutti


2 Answers

The following commandline and parsing can set environment/stage urls etc.

jest path/to/test.js '-stage=test'
# or...
npm test path/to/test.js -- -stage=test
// test.js
const stageArg = process.argv.filter((x) => x.startsWith('-stage='))[0]
const stage = stageArg ? stageArg.split('=')[1] : 'dev' // default
const apiUrl = stage === 'prod' ? 'https://api.mysite.com' : `https://api.${stage}.mysite.com`
const request = supertest(apiUrl)
// ...etc...

Not that you should be running tests on prod, but it can be handy for things such as pull data monitoring, eg check endpoint statuses:

expect((await request.get('/accounts/health')).body).toEqual(expected)
like image 94
Seba Illingworth Avatar answered Nov 12 '22 09:11

Seba Illingworth


I followed the following steps and worked for me. Hope this will guide you as well

Requrement * Parse username and password as command line parameters
Script

"scripts": {
"loginTest": "jest tests/Login.test.js"
}

Steps * In js file I added below to read command line arguments

exports.USER_NAME = require("minimist")(process.argv.slice(2))["username"];

But to work above method I had to update the script as follows

"scripts": {
"loginTest": "jest tests/Login.test.js [email protected]",
}

Then I found below method to parse argument into the script.

npm run loginTest -- [email protected]

With this, I was able to achieve my requirement without changing the script

like image 21
Jayanath Avatar answered Nov 12 '22 10:11

Jayanath