You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将主项目的baseURL传递给依赖的setup配置项目?

解决Playwright依赖项目传递baseURL的问题

方案1:让依赖项目继承主项目配置

修改setup项目的配置,使其自动继承调用它的主项目的use配置,这样运行不同主项目时,setup会获取对应的baseURL:

Projects: [
  { 
    name: 'setup', 
    testMatch: 'auth.setup.ts',
    use: {} // 空配置表示继承主项目的use设置
  },
  {
    name: 'e2e-uat',
    use: {
      baseURL: 'https://uat.example.com',
      storageState: '.auth/user.json',
    },
    dependencies: ['setup'],
  },
  {
    name: 'e2e-canary',
    use: {
      baseURL: 'https://example.com',
      storageState: '.auth/user.json',
    },
    dependencies: ['setup'],
  },
]

在auth.setup.ts中直接使用上下文的baseURL:

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

setup('authenticate', async ({ page, baseURL }) => {
  await page.goto(`${baseURL}/auth/login`);
  // 执行登录流程...
  await page.context().storageState({ path: '.auth/user.json' });
});

方案2:通过环境变量传递

在主项目配置中设置环境变量,setup中读取该变量:

修改项目配置

Projects: [
  { 
    name: 'setup', 
    testMatch: 'auth.setup.ts'
  },
  {
    name: 'e2e-uat',
    use: {
      baseURL: 'https://uat.example.com',
      storageState: '.auth/user.json',
    },
    dependencies: ['setup'],
    command: 'export BASE_URL=https://uat.example.com && playwright test'
  },
  {
    name: 'e2e-canary',
    use: {
      baseURL: 'https://example.com',
      storageState: '.auth/user.json',
    },
    dependencies: ['setup'],
    command: 'export BASE_URL=https://example.com && playwright test'
  },
]

在setup中读取环境变量

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

setup('authenticate', async ({ page }) => {
  const baseURL = process.env.BASE_URL || 'https://default.example.com';
  await page.goto(`${baseURL}/auth/login`);
  // 登录流程...
  await page.context().storageState({ path: '.auth/user.json' });
});

方案3:利用配置合并继承

抽离公共配置,让setup和主项目共享,主项目覆盖baseURL:

const commonUseConfig = {
  storageState: '.auth/user.json',
};

Projects: [
  { 
    name: 'setup', 
    testMatch: 'auth.setup.ts',
    use: commonUseConfig
  },
  {
    name: 'e2e-uat',
    use: {
      ...commonUseConfig,
      baseURL: 'https://uat.example.com',
    },
    dependencies: ['setup'],
  },
  {
    name: 'e2e-canary',
    use: {
      ...commonUseConfig,
      baseURL: 'https://example.com',
    },
    dependencies: ['setup'],
  },
]

这种方式下,Playwright会自动合并主项目与依赖项目的配置,setup运行时会获取主项目的baseURL。

内容的提问来源于stack exchange,提问作者Varun Sukheja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 06:45:13