username
username

Reputation: 159

How can I correctly resolve environment variables in Playwright tests for a React project built with Vite?

I'm encountering an issue with environment variable access in my tests for a project using Vite as a build tool alongside a React app. In the React app, environment variables are accessed via import.meta.env, but in our tests, we rely on process.env and .env files using the dotenv package.

I'm seeing the following error:

TypeError: Cannot read properties of undefined (reading 'MODE')

Could anyone suggest how to resolve this issue and properly access MODE within both the React app and the test environment?

# src/constants.ts

let BASE_URL: string;

const testMode = import.meta.env.MODE;

if (testMode === "testing") {
  BASE_URL = "http://testing.com";
} else if (testMode === "dev") {
  BASE_URL = "http://dev.com";
} else {
  BASE_URL = "http://production.com";
}

export { BASE_URL };
# playwright.config.ts


import { defineConfig, devices } from "@playwright/test";
import { BASE_URL as baseURL } from "./src/constants";
import dotenv from 'dotenv';

dotenv.config({ path:  '.env' });

export default defineConfig({
  testDir: "./e2e",
  fullyParallel: true,
  forbidOnly: !!process.env.CI,
  retries: process.env.CI ? 2 : 0,
  workers: process.env.CI ? 1 : undefined,
  reporter: "html",
  use: {
    baseURL // using the baseURL that is used by APP as well,
    trace: "on-first-retry",
  },

});

Link to the repo with repro example: https://github.com/omelnik/playwright-vite-repro

Upvotes: 3

Views: 1935

Answers (1)

Damzaky
Damzaky

Reputation: 10826

Why not simply add a fallback in the constant like:

const testMode = import?.meta?.env?.MODE || process?.env?.MODE;

if (testMode === "testing") {
  BASE_URL = "http://testing.com";
}
...

Upvotes: 0

Related Questions