jestjs - how to parametrize test execution from cli in ci?

i have 4 environments :

  • dev (developers area)
  • test (test area)
  • preprod (pre production environment)
  • production (production environment)

these environments needs different configuration to execute tests (differents urls, usernames, assets, and so on).

how to pass there configurations to jest as a parameter in continous integration?


As you can read here, jest would not permits to pass custom arguments you can use to handle custom configuration loaded at runtime.

i propose a workaround working for me.

  1. create a configuration file, e.g. config.js
  2. edit config.js and exports modules switching for the environment
switch (env) {
    case "test":
        module.exports = {
            baseUrl: 'https://test.website.com'
        }
        break;
    case "production":
        module.exports = {
            baseUrl: 'https://production.website.com'
        }
        break;

}

  1. create a javascript files for every environment you need
  • test-configuration.js
  • production-configuration.js
  1. edit these files writing in the environment variables

for example test-configuration.js will be

process.env.ENVIRONMENT = "test"
  1. load configuration for your test files as it was a static file
const config = require('./config.js')
  1. use jest setupFiles to add a setupFiles that load the environment variables.

for example, running

jest --setupFiles=./test-configuration.js

jest will load the test-configuration.js file that will set "test" on the "process.env.ENVIRONMENT" variables, so config.js file will "switch" on the "test" environment and all your test will use it.

so now you can (or CI can) loads configuration as needed.


For anyone facing the same issue – can't pass environment url to your custom setup file and tests. The solution might be dumb but it works without modifying the code much. In package.json modify your scripts to export environment before running jest:

  "scripts": {
    "test": "jest",
    "test:dev": "export ENVIRONMENT=https://dev.environment/ && jest",
    "test:prod": "export ENVIRONMENT=https://prod.environment/ && jest"
   }

Then you can access your code:

    const page = await browser.newPage();
    await page.goto(process.env.ENVIRONMENT);
    console.log(process.env.ENVIRONMENT);