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

Playwright:单个浏览器多标签页并行执行测试的可行性及实现方案

Playwright单浏览器多标签页并行测试实现方案

可行性确认

该场景完全可行。你当前遇到多浏览器串行执行的问题,是因为Playwright默认测试运行器会为每个测试用例独立初始化浏览器或上下文,导致实例隔离。只需手动控制浏览器、上下文和页面的生命周期,结合异步并行逻辑即可实现需求。

核心实现思路

  • 仅启动一个浏览器实例
  • 在该浏览器下创建单个上下文(或直接使用默认上下文)
  • 在上下文中创建多个页面(对应目标标签页)
  • 通过Promise.all()让不同页面的测试逻辑并行执行

代码示例(原生Playwright脚本)

const { chromium } = require('playwright');

(async () => {
  // 启动单个浏览器(headless设为false可可视化查看)
  const browser = await chromium.launch({ headless: false });
  
  // 创建单个上下文(统一管理标签页)
  const context = await browser.newContext();
  
  // 创建两个标签页
  const tab1 = await context.newPage();
  const tab2 = await context.newPage();

  try {
    // 并行执行Test1和Test2
    await Promise.all([
      // Test1:Tab1的测试逻辑
      (async () => {
        await tab1.goto('https://example.com');
        await tab1.waitForSelector('h1');
        const title = await tab1.title();
        console.log('Test1完成,页面标题:', title);
      })(),
      // Test2:Tab2的测试逻辑
      (async () => {
        await tab2.goto('https://playwright.dev');
        await tab2.waitForSelector('h1');
        const title = await tab2.title();
        console.log('Test2完成,页面标题:', title);
      })()
    ]);
  } finally {
    // 测试结束后关闭浏览器
    await browser.close();
  }
})();

基于Playwright Test框架的实现

如果使用Playwright官方测试框架,需先禁用默认的测试隔离机制,再手动共享浏览器实例:

1. 修改配置文件(playwright.config.js)

module.exports = {
  use: {
    // 禁用测试隔离,允许共享上下文和页面
    testIsolation: false,
  },
};

2. 编写测试用例

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

test('单浏览器多标签页并行测试', async ({ browser }) => {
  const context = await browser.newContext();
  const tab1 = await context.newPage();
  const tab2 = await context.newPage();

  // 并行执行页面跳转
  await Promise.all([
    tab1.goto('https://example.com'),
    tab2.goto('https://playwright.dev')
  ]);

  // 执行断言逻辑
  await test.expect(tab1.locator('h1')).toHaveText('Example Domain');
  await test.expect(tab2.locator('h1')).toHaveText('Playwright');

  // 清理上下文
  await context.close();
});

关键注意事项

  • 禁止在每个测试用例中单独调用browser.launch()或context.newContext(),否则会创建新的浏览器/上下文实例,回到你之前遇到的多浏览器问题。
  • 并行执行时要注意页面操作的独立性,避免不同测试逻辑互相干扰。

内容的提问来源于stack exchange,提问作者Shilpa sampath

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 02:33:14