In this example we will explore how to use dotenv in Playwright. Using dotenv in a Playwright project is a great way to manage environment variables securely. Below is a detailed step-by-step guide with a working example on how to integrate dotenv into a Playwright test setup.
Install Dependencies
First, you need dotenv installed alongside Playwright.
npm install dotenv npm install -D @playwright/test
Project Structure
Your folder might look like this:
Create a .env File
BASE_URL=https://example.com LOGIN_USER=testuser LOGIN_PASS=securepassword123
Load dotenv in the Playwright Config
In your playwright.config.ts (or .js), import and configure dotenv at the top:
// playwright.config.ts import { defineConfig } from '@playwright/test'; import * as dotenv from 'dotenv'; dotenv.config(); // Load variables from .env export default defineConfig({ use: { baseURL: process.env.BASE_URL, // use env variable }, });
Using .env in Your Test Files
Now, inside a test file (e.g., tests/example.spec.ts), you can also use the environment variables:
// tests/example.spec.ts import { test, expect } from '@playwright/test'; test('login using credentials from .env', async ({ page }) => { await page.goto('/login'); // uses baseURL from config await page.fill('#username', process.env.LOGIN_USER || ''); await page.fill('#password', process.env.LOGIN_PASS || ''); await page.click('button[type="submit"]'); await expect(page).toHaveURL('/dashboard'); });
This is all about how to use dotenv in playwright.
No comments:
Post a Comment