Home > database >  How to use .env variables inside cypress.json file?
How to use .env variables inside cypress.json file?

Time:12-15

I want to use my .env variables inside cypress.json file. As an example of usage:


    {
      "env": {
        "HOST": `${process.env.HOST}`
      }
    }

So, what I want is, when I type Cypress.env('HOST') anywhere in Cypress, I want to get the process.env.HOST variable

CodePudding user response:

First of all why not use process.env.HOST inside your spec files. Second if you want to test in different host then what i have been doing is.

  1. Create a folder (eg: configFiles)

  2. Inside this create json files like (eg: host1.json, host2.json)

  3. Inside your json file (in host1.json)

    { "env": { "HOST" : "host1" } }

  4. Inside your plugins folder edit index.js

    const fs = require('fs-extra'); const path = require('path');

    function getConfigurationByFile(file) { const pathToConfigFile = path.resolve( 'cypress/configFiles', ${file}.json );

    return fs.readJson(pathToConfigFile); }

    module.exports = (on, config) => { const file = config.env.host || 'host1';

    return getConfigurationByFile(file); };

  5. Then while running you can use npm cypress run --env host=host1

CodePudding user response:

Avoid wrapping your env file in env variable. By the way this should do the job with your file:

Cypress.env("env")["HOST"]
  • Related