如何在Playwright中为测试指定目标项目(桌面/移动端)
无需拆分项目的解决方案
直接用Playwright的多Project配置结合标签/目录划分就能搞定,给你几个实用方案:
方案1:测试标签+Project过滤
给不同端的测试打标签,然后在配置里指定每个Project只跑对应标签的测试,灵活度最高。
步骤1:给测试打标签
在测试文件里给移动端/桌面端测试分别添加标签:
// 移动端专属测试 test('提交表单(移动端)', { tag: '@mobile' }, async ({ page }) => { // 你的移动端测试逻辑 }); // 桌面端专属测试 test('提交表单(桌面端)', { tag: '@desktop' }, async ({ page }) => { // 你的桌面端测试逻辑 });
步骤2:配置Project的标签过滤规则
在playwright.config.js里更新多Project配置,给每个Project加上标签过滤:
const { defineConfig, devices } = require('@playwright/test'); module.exports = defineConfig({ projects: [ { name: 'desktop', use: { // 你的桌面端浏览器配置(如chromium、firefox等) headless: true, // ...其他桌面端专属配置 }, includeTags: ['@desktop'], // 只运行带@desktop标签的测试 }, { name: 'mobile', use: { ...devices['iPhone 12'], viewport: { width: 390, height: 844 }, headless: false, video: 'on-first-retry' }, includeTags: ['@mobile'], // 只运行带@mobile标签的测试 }, ], });
步骤3:命令行指定Project运行
# 运行所有桌面端测试 npx playwright test --project=desktop # 运行所有移动端测试 npx playwright test --project=mobile
方案2:按目录划分测试文件
如果不想打标签,直接把移动端和桌面端测试放在不同目录,用testMatch配置匹配对应目录的文件。
步骤1:整理测试文件结构
tests/ ├── desktop/ # 桌面端测试文件 │ ├── login.spec.js │ └── checkout.spec.js └── mobile/ # 移动端测试文件 ├── login.spec.js └── checkout.spec.js
步骤2:配置Project的文件匹配规则
在playwright.config.js里更新配置:
const { defineConfig, devices } = require('@playwright/test'); module.exports = defineConfig({ projects: [ { name: 'desktop', use: { /* 桌面端配置 */ }, testMatch: 'tests/desktop/**/*.spec.js', // 只匹配desktop目录下的测试文件 }, { name: 'mobile', use: { ...devices['iPhone 12'], viewport: { width: 390, height: 844 }, headless: false, video: 'on-first-retry' }, testMatch: 'tests/mobile/**/*.spec.js', // 只匹配mobile目录下的测试文件 }, ], });
步骤3:命令行运行
和方案1一样,指定Project即可:
npx playwright test --project=desktop npx playwright test --project=mobile
方案3:测试内条件跳过(适合临时场景)
如果不想改配置或目录,直接在测试里判断当前运行的Project名称,跳过不符合的测试:
test('移动端专属测试', async ({ page }) => { // 获取当前运行的Project名称(Playwright自动注入环境变量) const currentProject = process.env.PLAYWRIGHT_PROJECT; if (currentProject !== 'mobile') { test.skip(); // 非mobile环境直接跳过 } // 测试逻辑 }); test('桌面端专属测试', async ({ page }) => { const currentProject = process.env.PLAYWRIGHT_PROJECT; if (currentProject !== 'desktop') { test.skip(); } // 测试逻辑 });
以上三种方案都不需要拆分项目,推荐用方案1或2,维护起来更清晰规范。
内容的提问来源于stack exchange,提问作者valk
相关产品推荐
相关产品推荐

