How to use process.env variables in browser running by Cypress?
Last Updated :
24 Oct, 2024
In modern-day web applications, testing plays a really vital role in keeping up the integrity of the software. Cypress has become a very popular choice due to its simplicity & robust features. One common challenge is securely handling the specific environment variables like API Keys and secret tokens, particularly when these tests are running on the browser environment.
Cypress gives amazing support for environment variables through " process.env ". However, taking care of these environment variables within the browser setting needs an extraordinary approach since web browser scripts cannot straightforwardly access environment variables.
Step-by-Step Code Implementation
Step 1: Install the Cypress Plugin
Firstly, we have to install the Cypress plugin, by using the npm command :
JavaScript
npm install cypress --save-dev
Installation of CypressStep 2: Open the Cypress Test Runner
After installing Cypress plugin we have to Open the Cypress Test Runner window , using the following command:
JavaScript
Open Cypress Test Runner Console This will open the Cypress Test Runner and also check whether the default Test Case of Cypress is Running or Not in your System. Please Select the specific Test File to run the Test Cases or to create " Create New Spec Section " to create the new Test File for Running Test Cases.
Step 3: Project Structure Looks like
Project StructureStep 4: Define the Environment Variables
In Cypress , environment variables are defined in a few different ways, such as in " cypress..config.js / cypress.config.ts " files. Another option is to pass the environment variables directly through CLI during running the Test Case.
Let's define the environment variable in the " cypress..config.js / cypress.config.ts " file.
JavaScript
const { defineConfig } = require('cypress');
module.exports = defineConfig({
e2e: {
env: {
MY_API_KEY: '123456789abcdef'
},
viewportWidth: 1280,
viewportHeight: 720
}
});
Step 5: Create Custom Command to Expose Environment Variable to the Browser
- Cypress has the " process.env " method to access all the environment variable. To make environment variable available to the browser, you need to pass them explicitly.
- Custom Cypress command to inject the environment variable into your tests.
- In the " cypress/support/command.js ", please add this custom command to expose Environment Variable for the specific test case.
JavaScript
Cypress.Commands.add('getEnvVar', (envVarName) => {
return Cypress.env(envVarName);
});
Step 6: Access the Environment Variable in your Test case
Now after configuring custom command in " commands.js " Now the Test file are allowed to access the environment variable & pass them into the browser.
Step 7: Run Cypress Test with Environment Variable
Now you can Run the Cypress Test Case with specific environment variable in two ways:
- Directly From CLI with API Key: Pass the environment variable when you run Cypress via command line.
JavaScript
npx cypress run --env MY_API_KEY=abcdef123456
- By using command : To run the Test Case in the Cypress use the following command .
JavaScript
// without API Key
npx cypress run
// with API Key
npx cypress run --env MY_API_KEY=123456789abcdef
// Run the Specific Test Case
npx cypress run --spec "cypress/e2e/env_test.cy.js"
Output:
- Check Output In Cypress GUI : Once we run the test cases , we are going the result of our test cases in real-time with step-by-step logs & preview of the execution of the test cases , including the Test PASSED or Test FAILED.
- Check Output in Headless Mode : After Running " npm cypress run " we are ready to see the output in the terminal , which includes test passes , failures and any other error related message.
Example of Output Illustrated:
For example, when running the above test cases , if in case Our API Key & process.env configured Correctly , then test will PASSED.
JavaScript
assert : expected <window> to have property
✓ apiKey** of **123456789abcdef
If incase there might be some particular issue with API Key (like Mismatch or Not correct) or not properly configured process.env , we will see the FAILURE Message in the Cypress Test Runner Console .
JavaScript
assert expected <window> to have property
apiKey** of **123456789abcdefg ,
X **but got 123456789abcdefg
Test Failed due to Different Environment VariableFor passed test cases output:
PASSED Test Case Validate process.env , accessible in browserFor failed test cases output:
FAILED Test Case , doesn't Validate environment varConclusion
By utilizing environment variables into your Cypress test it is essential for keeping you sensitive data secure while ensuring your tests are flexible & adaptable to different environments. By using above steps we can safely use " process.env " variable in your browser-based Cypress test.
Similar Reads
How To Configure And Use Environment Variables in NestJS?
Environment variables are an important part of application development, allowing developers to configure applications in different environments (development, staging, production) without hardcoding sensitive or environment-specific information into the application code. In this article, we'll walk t
2 min read
Environment Variables in Cypress
Cypress is a modern front-end test instrument. One can write strong, reliable end-to-end tests using Cypress which should ensure that applications are running smoothly and securely. A vital aspect of the flexibility and maintainability of Cypress tests lies in its utilization of environment variable
11 min read
How to use values from DOM in cypress test?
Ensuring that applications function correctly in web development is vital for providing a seamless user experience. Cypress has become a go-to testing framework for developers, offering powerful capabilities for end-to-end testing. One of the essential tasks in testing is validating the values displ
3 min read
How do I get Cypress just to process the visible element?
When writing Cypress tests, you might encounter elements that are either hidden by default or not visible due to styling (like display: none). To avoid Cypress trying to interact with such elements, you can leverage the .should('be.visible') command. This assertion guarantees that the test will only
2 min read
How to use CSS variables with TailwindCSS ?
Tailwind CSS  allows users to predefined classes instead of using the pure CSS properties. We have to install the Tailwind CSS.  Create the main CSS file (Global.css) which will look like the below code. Global.css: In the following code, the entire body is wrapped into a single selector. The entir
1 min read
How to print a variable directly using EJS template engine?
EJS (Embedded JavaScript) is a templating engine for NodeJS that enables dynamic content generation in web applications. To print a variable directly in an EJS template, you can use the <%= variable %> syntax. This syntax allows you to embed and display the value of a variable directly within
2 min read
Access environment variable values in Python
An environment variable is a variable that is created by the Operating System. Environment variables are created in the form of Key-Value pairs. To Access environment variables in Python's we can use the OS module which provides a property called environ that contains environment variables in key-va
3 min read
How to get text from an element and store in a variable in Cypress?
In Cypress, it's common to retrieve the text content from an element and use it for further actions or assertions. To store the extracted text in a variable for later use, Cypress provides commands like .then() or .invoke(), allowing you to handle the value outside of the usual Cypress chain. In thi
3 min read
Cypress - Get Attribute value and store in Variable
In Cypress, you can retrieve an attribute value of an element using the .invoke() method. This is helpful when you need to store an attribute value for further use in your test. For instance, you might want to grab the value of a href, id, or src attribute from an element and then perform assertions
3 min read
How to Access EJS Variable in Javascript Logic ?
EJS stands for Embedded JavaScript. It is a templating language used to generate dynamic HTML pages with data from the server by embedding JavaScript code. Features of EJSDynamic Content: Based on data from servers or other sources, we can generate a dynamic HTML template.Partial Templates: Partials
3 min read