Skip to content

Instantly share code, notes, and snippets.

@Josh68
Created May 20, 2021 16:44
Show Gist options
  • Save Josh68/158c4caf6b0dc76f7db02a667943199d to your computer and use it in GitHub Desktop.
Save Josh68/158c4caf6b0dc76f7db02a667943199d to your computer and use it in GitHub Desktop.
Cypress using .env variables
/**
* All files in /cypress/plugins, but only index.js needs to be there
* With Webpack (and now just modern Node) most imports and exports could be ES6, AFIAK
* index.js still does a `module.exports`
*
* Plugins enable you to tap into, modify, or extend the internal behavior of Cypress.
* @see https://on.cypress.io/plugins-guide
*/
/**
* Sets the Cypress test base URL
*
* Looks for the `MY_PROJECT_URL`, defaults to an empty string.
* @param {Object} processEnv The `process.env` object
* @returns {string} The Cypress base URL
*/
const baseUrl = processEnv => processEnv.MY_PROJECT_URL || '';
module.exports = baseUrl;
/**
* /cypress/plugins/my-env-vars.js
* List of custom environment variables; found in `.env` file
*/
module.exports = ['A_PASSWORD', 'A_PATH', 'A_SECRET'];
/**
* /cypress/plugins/custom-env-vars.js
*
* Collects given environment variables into a tidy usable object
* @param {Object} processEnv The `process.env` object
* @param {Array} customVars A list of custom environment variables
*/
const customEnvVars = (processEnv, customVars = []) =>
customVars.reduce((acc, envVar) => {
acc[envVar] = processEnv[envVar];
return acc;
}, {});
module.exports = customEnvVars;
/**
* /cypress/plugins/index.js
* Allows reading of environment variables from `.env` file
* @see github.com/motdotla/dotenv
* For variable expansion:
* @see github.com/motdotla/dotenv-expand
*/
require('dotenv').config();
const baseUrl = require('./base-url');
const myEnvVars = require('./my-env-vars');
const customEnvironmentVariables = require('./custom-env-vars');
module.exports = (on, config) => {
// `on` is used to hook into various events Cypress emits
// `config` is the resolved Cypress config
// Set Cypress base URL
config.baseUrl = baseUrl(process.env);
// Set Cypress environment variables needed to run the tests
config.env = customEnvironmentVariables(process.env, myEnvVars);
return config;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment