Playwright URL 配置 - 多个应用程序和不同基本 url 的环境变量

问题描述 投票:0回答:2

为项目配置和使用 url 的最佳方法是什么

  • 2x 网络应用程序
  • 3x 环境

...我们有这样的情况作为例子

水果应用

  • 基本网址:
    • dev.fruits.com
    • test.fruits.com
    • prod.fruits.com
  • 端点:
    • /香蕉/
    • /猕猴桃/
    • /苹果/

颜色应用程序

  • 基本网址:
    • dev.colors.com
    • test.colors.com
    • prod.colors.com
  • 端点:
    • /红色/
    • /蓝色/
    • /绿色/

...以及这样的测试


    test('Navigate to fruits/banana', async () => {
      await page.goto('https://https://dev.fruits.com/banana/');
      ...
    });
     
    test('Navigate to colors/red', async () => {
      await page.goto('https://https://dev.colors.com/red/');
      ...
    });

...我想去的地方

  1. 用 baseurl 变量替换 dev.fruits.com 和 dev.colors.com
  2. “开发”部分应该是动态的,具体取决于我运行测试的环境
automated-tests playwright base-url
2个回答
10
投票

您可以使用单独的项目来进行不同的配置:

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

/**
 * @see https://playwright.dev/docs/test-configuration
 * @type{import('@playwright/test').PlaywrightTestConfig}
 */
const config = {
  projects: [
    {
      name: 'Fruit Dev',
      testMatch: 'fruits/**/*',
      use: {
        baseURL: 'https://dev.fruits.com'
      }
    },
    {
      name: 'Fruit Test',
      testMatch: 'fruits/**/*',
      use: {
        baseURL: 'https://test.fruits.com'
      }
    },
    {
      name: 'Fruit Prod',
      testMatch: 'fruits/**/*',
      use: {
        baseURL: 'https://test.fruits.com'
      }
    },
    {
      name: 'Color Dev',
      testMatch: 'colors/**/*',
      use: {
        baseURL: 'https://dev.colors.com'
      }
    },
    {
      name: 'Color Test',
      testMatch: 'colors/**/*',
      use: {
        baseURL: 'https://test.colors.com'
      }
    },
    {
      name: 'Color Prod',
      testMatch: 'colors/**/*',
      use: {
        baseURL: 'https://test.colors.com'
      }
    },
  ]
};
module.exports = config;


5
投票

我最近遇到了这个问题,作为使用项目的替代方案,我使用了 env 配置文件(如

dotenv
),因为我们的大多数代码库都使用相同的文件。在本例中,我根据测试环境而不是所使用的应用程序对其进行分类。

我使用示例 json 文件创建了一个

config
文件夹:
config/dev.env.json

config/test.env.json

config/prod.env.json

包含以下内容:

{
  "fruitApp": {
    "baseUrl": "prod.fruits.com",
    "endpoints": {
      "banana": "/banana/",
      "kiwi": "/kiwi/",
      "apple": "/apple/"
    }
  },
  "colorApp": {
    "baseUrl": "prod.colors.com",
    "endpoints": {
      "banana": "/red/",
      "kiwi": "/blue/",
      "apple": "/green/"
    }
  }
}

然后在

playwright.config.ts
,我有以下片段:

const config = process.env.ENV || 'prod';
const env = require(`./config/${config}.env.json`); // load env from json

export default defineConfig({
  ...env,

在您的规范/测试文件中,您可以使用以下方式调用上述内容:

console.log(env.fruitApp.baseUrl)

运行测试:

ENV=prod npx playwright test
© www.soinside.com 2019 - 2024. All rights reserved.