NextJS项目中,如何用Playwright让特定文件夹测试串行、其余并行?
实现Playwright特定文件夹测试串行执行
针对你的Next.js项目需求,要让/onboard文件夹下的测试串行运行,其他测试保持并行,可以通过以下步骤实现:
1. 配置Playwright测试项目
在playwright.config.ts中新增一个专门的测试项目,指定目标文件夹路径并强制串行执行:
import { defineConfig, devices } from '@playwright/test'; export default defineConfig({ // 全局默认并行配置,CI环境可按需调整 workers: process.env.CI ? 2 : undefined, projects: [ // 原有并行测试项目,排除需要串行的文件夹 { name: 'chromium', use: { ...devices['Desktop Chrome'] }, testMatch: '**/*.spec.ts', testIgnore: '**/onboard/**/*.spec.ts', }, // 串行执行的onboard测试项目 { name: 'onboard-serial', use: { ...devices['Desktop Chrome'] }, testMatch: '**/onboard/**/*.spec.ts', workers: 1, // 强制同一时间只运行一个测试文件,实现串行 }, ], });
2. 保证测试文件执行顺序
Playwright默认按文件名排序执行测试文件,给/onboard下的文件添加顺序前缀,确保依赖流程正确:
01-create-account.spec.ts(创建账户)02-verify-otp.spec.ts(验证OTP)03-fill-questionnaire.spec.ts(填写问卷)
3. 传递测试间的状态依赖
因为测试是分文件的,需要把创建账户后的登录状态传递给后续测试,用Playwright的storageState实现:
创建账户的测试文件(01-create-account.spec.ts)
import { test } from '@playwright/test'; import path from 'path'; test('创建用户账户并保存状态', async ({ page }) => { await page.goto('/onboard'); // 执行账户创建流程:填写邮箱、密码等步骤 await page.fill('[name="email"]', 'test-onboard@example.com'); await page.fill('[name="password"]', 'secure123'); await page.click('button[type="submit"]'); // 等待重定向到验证页面,确认账户创建成功 await page.waitForURL('/onboard/verify'); // 保存当前上下文的登录状态到文件 await page.context().storageState({ path: path.join(__dirname, '../.auth/onboard-user.json') }); });
验证OTP的测试文件(02-verify-otp.spec.ts)
import { test } from '@playwright/test'; import path from 'path'; // 加载之前保存的账户状态,直接处于登录后的上下文 test.use({ storageState: path.join(__dirname, '../.auth/onboard-user.json') }); test('验证邮箱OTP', async ({ page }) => { await page.goto('/onboard/verify'); // 模拟输入OTP(实际项目中可从邮件服务获取) await page.fill('[name="otp"]', '123456'); await page.click('button[type="submit"]'); await page.waitForURL('/onboard/questionnaire'); });
填写问卷的测试文件(03-fill-questionnaire.spec.ts)
同样加载storageState,直接进入问卷页面操作即可,无需重复创建账户。
4. 运行测试
- 单独运行串行测试:
npx playwright test --project=onboard-serial - 同时运行所有测试(并行项目和串行项目会同时启动,串行项目内部按顺序执行):
npx playwright test
额外注意事项
- 每次运行前清理旧的状态文件,避免残留数据干扰:可以在
playwright.config.ts中配置globalSetup来自动清理.auth文件夹 - CI环境中确保
.auth文件夹被纳入临时文件目录,避免权限问题
内容的提问来源于stack exchange,提问作者Xyeut
相关产品推荐
相关产品推荐

