尝试从 .env 文件中读取值会在编剧中抛出未定义的错误

Trying to read value from .env file throws undefined error in playwright

我无法在 playwright 测试中从 .env 文件中获取 url 值,而 运行 测试则抛出错误 baseURL of undefined ,有人可以就这个问题提出建议吗? 类型错误:无法读取未定义的 属性 'baseURL'

  10 | test('Access the Playwright Page', async ({ page }) => {
  11 |   const playwrightDev = new PlaywrightDevPage(page);
> 12 |   await playwrightDev.goto(Config.baseURL);
     |                                   ^

以下是我的 .env 文件。

URL=https://playwright.dev/

下面是我的playwright.config.js文件和设置

const { devices } = require('@playwright/test');

/** @type {import('@playwright/test').PlaywrightTestConfig} */

const config = {
  forbidOnly: !!process.env.CI,
  retries: process.env.CI ? 2 : 0,
  use: {
    trace: 'on-first-retry',
    baseURL: process.env.URL,
  },
  projects: [
    {
      name: 'chromium',
      use: { ...devices['Desktop Chrome'] },
    },
  ],
};

module.exports = config;

下面是我的example.spec.js文件

const { test, expect } = require('@playwright/test');
const { PlaywrightDevPage } = require('./playwright-dev-page');
const { Config } = require('../playwright.config');

test('Access the Playwright Page', async ({ page }) => {
  const playwrightDev = new PlaywrightDevPage(page);
  await playwrightDev.goto(Config.baseURl);
 
});

您需要通过以下方式在您的配置中加载 dotenvrequire('dotenv').config()

然后您可以在测试中使用“dotenv 文件”的环境变量,例如:process.env.FOOBAR

dotenv 用法见这里:https://www.npmjs.com/package/dotenv