username
username

Reputation: 159

How to Leverage Vite's Built-in Mechanism to Pass Environment Variables to Playwright

I'm currently working on a project where I need to use Playwright for end-to-end testing, and I'm using Vite as my frontend build tool. I want to pass environment variables from Vite to Playwright, but I'm not sure how to achieve this integration seamlessly. Specifically, I need to pass variables such as API URLs, authentication tokens, and other configuration settings to my Playwright tests.

I've looked into Playwright's documentation, and it seems like there isn't a straightforward way to directly access Vite's environment variables within my test scripts. Is there a recommended approach or workaround for achieving this?

Question:

I appreciate any insights or guidance on this matter. Thank you!

Upvotes: 1

Views: 664

Answers (1)

Iaroslav Sobolev
Iaroslav Sobolev

Reputation: 1244

vite is a bundler and it has it's own mechanism to utilize env variables. Playwright by default doesn't know anything about vite and their env variables. docs.

What you can do is define .env file with env variables you need and then use it both: vite and playwright. For Playwright you need to parametrize tests

.env:

VITE_API_URL=https://someapi.com/api

parametrized test /my-test.ts:

import { test as base } from '@playwright/test';

export type TestOptions = {
  apiUrl: string;
};

export const test = base.extend<TestOptions>({
  // Define an option and provide a default value.
  // We can later override it in the config.
  apiUrl: ['/', { option: true }],
});

configure playwright.config.ts:

import { defineConfig } from '@playwright/test';
import dotenv from 'dotenv';
import type {TestOptions} from './my-test'

// Read from default ".env" file.
dotenv.config();

export default defineConfig<TestOptions>({
  use: {
    apiUrl: process.env.VITE_API_URL
  }
});

example.spec.ts:

import { test } from './my-test';

test('test 1', async ({ page, apiUrl }) => {
    // you can use apiUrl here
});

and from frontend app index.ts/js

console.log(import.meta.env.VITE_API_URL) 

Upvotes: 2

Related Questions