Harnessing the Power of process.env in Playwright

Cerosh Jacob
4 min readSep 12, 2023

--

Photo by Joshua Sortino on Unsplash

Efficiently managing test data and ensuring secure and maintainable scripts are paramount in the world of automated testing with Playwright. This article explores how to streamline data sharing between test cases, particularly when dealing with unique item IDs in URLs, using Playwright’s process.env. Discover how this approach enhances testing flexibility, security, and script maintainability.

The process.env object is a global object in Node.js that provides access to the environment variables set when the Node.js process starts. These environment variables are used to configure the behaviour of the Node.js process and pass configuration information to a program without hardcoding it into the program's source code. This makes it easier to deploy the program to different environments, such as development, staging, or production.

Environment variables have been used in test automation for many years. Initially, they were used to pass configuration information to test scripts, such as the URL of the website to test, the username and password to use, or the browser to use. As test automation frameworks have become more sophisticated, environment variables have been used to configure the behaviour of the test framework itself, such as the number of tests to run, the timeout for each test, or the logging level.

The dotenv library is used to load environment variables from a .env file into the process.env object. The .env file is a text file that contains environment variables in the format KEY=VALUE. Although you can still use the dotenv library, Node.js 18 has introduced a new built-in way to load environment variables from a .env file. This new way is called process.env.setContext(), which takes a context object as an argument. The context object can contain environment variables. For example, the following code would set the DATABASE_URL environment variable in the context:

const context = {
DATABASE_URL: 'localhost:5432',
};
process.env.setContext(context);

Once the context has been set, you can access the environment variables in the context using the process.env object. For example, the following code would get the value of the DATABASE_URL environment variable:

const databaseUrl = process.env.DATABASE_URL;

The new built-in way to load environment variables is more secure than the dotenv library because it does not expose environment variables in the source code.

Let’s consider a scenario in which a user adds an item in one test case. Once the item is successfully added, a unique ID is generated and displayed in the URL. In a subsequent test case, the user wants to delete the same item. The user can directly use the ID from the URL to delete the item. If the ID is not known, the user needs to search for and select the item before deleting it.

Using process.env can save time by transferring test data between test cases and ensuring the delete function works correctly. It's also useful for storing configuration variables, such as database connection strings or API keys, which prevents sensitive information from being hardcoded into your code. process.env is flexible and can be customized for various environments, such as development, testing, and staging. This feature enhances the security, maintainability, and flexibility of your test scripts.

Data sharing in the above example will be a two-step process. First, extract the last part of the pathname from the URL of the current page and store it in the itemId environment variable.

const urlString = this.page.url()
try {
const url = new URL(urlString);
const pathname = url.pathname;
process.env.itemId = pathname.substring(pathname.lastIndexOf('/') + 1);
} catch (error) {
console.error('Invalid URL:', error);
}

To handle URL parsing errors, the code includes a try-catch block that prints an error message to the console if an error occurs. The URL constructor creates a new URL object from urlString, which enables the code to parse and access various URL components. The pathname property extracts the pathname from the URL, while the lastIndexOf() method finds the last forward slash (/) in the pathname.

const itemId = process.env.itemId ?? 'invalid Item Id’

Retrieving data from an environment variable is fairly easy. To assign the value of process.env.itemId to the variable itemId, use the nullish coalescing operator (??). If process.env.itemId is not null or undefined, itemId will be assigned the value of process.env.itemId. If process.env.itemId is null or undefined, itemId will be assigned the fallback value 'invalid Item Id'.

The process.env variable is only available in Playwright scripts executed in a Node.js environment. The environment variables available in process.env are determined by the environment in which the Playwright script is executed. For instance, if the script runs on a CI server, the environment variables set on the CI server will be available in process.env.

My recent publication compiled a comprehensive collection of 100 similar typescript programs. Each program not only elucidates essential Typescript concepts and expounds upon the significance of test automation but also provides practical guidance on its implementation using Playwright. This resource will undoubtedly be valuable if you look deeper into similar topics.

--

--

No responses yet