Bruno 的 Playwright 端到端测试指南:基于 UI 录制、编写与维护 Electron 应用的测试用例

原创2026-09-08 21:10:231,976 阅读
文章标签:开发工具接口测试测试桌面应用API设计CLI

Bruno 的 Playwright 端到端测试指南:基于 UI 录制、编写与维护 Electron 应用的测试用例

本指南完整讲解如何为 Bruno(开源 API 客户端)编写和运行 Playwright 端到端测试。Bruno 的测试体系以 playwright/index.ts 中封装的一组自定义 Fixture 为核心,覆盖 Electron 应用的启动、临时用户数据目录隔离、页面就绪等待与 Trace 录制等场景。读完本文你将掌握:用 test:codegen 录制生成用例、按 page-module 模式手工编写稳定用例、利用 fixtures 隔离测试数据,以及在 CI 与本地高效运行与排障的完整方法。

概览:为什么 Bruno 需要这样一套测试体系

Bruno 是一款基于 Electron 的桌面 API 客户端(其运行逻辑集中在 packages/bruno-electron),端到端测试必须真正拉起 Electron 窗口并模拟用户操作。仓库为此在 Playwright 之上搭建了专门设施,集中在两个地方:

  • playwright/index.ts:test 对象的扩展定义处,注册全部自定义 fixture、defaultPreferences 默认偏好、waitForReadyPage 等待逻辑与 closeElectronApp 优雅关闭逻辑;
  • playwright/codegen.ts 与 playwright/electron.ts:分别实现 UI 录制(codegen)与 Electron 应用启动的底层封装。

整个测试套件分布在 tests 目录下,按功能域(collection/、environments/、runner/、websockets/、graphql/、auth/、ssl/、proxy/ 等)组织成大量 *.spec.ts 用例文件。

环境准备(Prerequisites)

在编写或运行任何用例之前,请确保满足以下条件:

  1. 已安装 Node.js;
  2. 已安装全部依赖:在仓库根目录执行 npm install(Playwright 相关依赖 @playwright/test 与 playwright 的版本由根 package.json 锁定为 1.62.1);
  3. Electron 应用可被构建并运行——可通过 npm run dev:electron 先行手动启动验证。

通过 Codegen 创建测试

录制交互生成用例是上手最快的方式。

内置 Codegen 脚本

仓库在根 package.json 注册了 test:codegen 脚本,其实现见 playwright/codegen.ts:

# 生成指定名称的测试(无扩展名时自动追加 .spec.ts 并落到 tests/ 目录)
npm run test:codegen my-new-test

# 不指定名称时交互式等待输入
npm run test:codegen

Codegen 内部发生了什么

对照 playwright/codegen.ts 源码,流程如下:

  1. 先执行 startApp()(见 playwright/electron.ts):通过 electron.launch({ args: [electronAppPath] }) 拉起 packages/bruno-electron,并将子进程的 stdout/stderr 按行加上 [Electron] | 前缀转发到当前终端;
  2. Playwright Inspector(录制器)在独立窗口中打开;
  3. 你在 Bruno 界面中执行操作,Inspector 将动作录制成 playwright-test 语言的测试代码;
  4. 输出文件按规则保存:若第 2 个命令行参数已是 .ts/.js 结尾则原样使用,否则写入 tests/<name>.spec.ts(见 playwright/codegen.ts)。

Codegen 推荐工作流

  1. 开始录制:运行 npm run test:codegen <test-name>;
  2. 操作界面:执行想要测试的用户流程;
  3. 添加断言:在 Inspector 中选中元素后点击断言按钮(如 “Assert text”、”Assert visible”);
  4. 保存用例:录制器自动生成测试文件;
  5. 评审并打磨:将生成文件里的裸选择器抽取到 page module,并补充分组与数据隔离。

录制器生成的第一版代码通常直接内联了 page.locator(...)/getByTestId(...) 选择器,这在正式提交前应按下文 “Best Practices §1” 重构为 page module 风格,保证选择器单一来源。

手工创建测试

需要精确控制步骤、参数化或复现边界条件时,可完全手工编写。

基础测试结构

所有用例都从仓库自定义的 playwright/index.ts 导出 test/expect(文件末尾 export * from '@playwright/test' 同时转发了标准 API),因此统一写 from '../../playwright':

import { test, expect } from '../../playwright';

test('Test description', async ({ page }) => {
  // Test steps here
  await page.getByLabel('Some Label').click();

  // Assertions
  await expect(page.getByText('Expected Text')).toBeVisible();
});

使用临时数据的测试

借助 createTmpDir fixture 为每次测试生成独立临时目录,保证测试互不污染(底层使用 fs.mkdtemp,见 playwright/index.ts):

import { test, expect } from '../../playwright';

test('Test with temporary data', async ({ page, createTmpDir }) => {
  // Create temporary directory for test data
  const testDir = await createTmpDir('test-collection');

  // Test steps
  await page.getByLabel('Create Collection').click();
  await page.getByLabel('Name').fill('test-collection');
  await page.getByLabel('Location').fill(testDir);

  // Assertions
  await expect(page.getByText('test-collection')).toBeVisible();
});

测试结构与组织

目录结构

仓库根配置 playwright.config.ts 的 default project 将 testDir 指向 ./tests,因此目录约定如下:

tests/
├── <功能域>/                        # 例如 collection、environments、runner、websockets、graphql
│   ├── xxx.spec.ts                  # 用例文件
│   ├── fixtures/                    # 可选的布鲁/yml/json 测试数据(.bru 集合文件、workspace 等)
│   └── init-user-data/              # 可选的初始用户数据(preferences.json 等)
└── utils/
    ├── page/                        # 页面模块(locator 构建器 + 动作,见 Best Practices §1)
    │   ├── locators.ts              # buildCommonLocators:汇总全部子模块 locator
    │   ├── actions.ts               # 通用动作辅助函数(createCollection、createRequest……)
    │   ├── mounting.ts              # 集合树装载/展开/结构断言等
    │   ├── sidebar/ environments/ request/ runner/ websocket/ …(各功能域模块)
    └── snapshot.ts 等               # 通用工具

关于 fixtures/ 与 init-user-data/ 的约定,可对照 fixture 实现确认:collectionFixturePath/workspaceFixturePath 会自动把测试同目录下 fixtures/collection、fixtures/collections 或 fixtures/workspace 拷贝到临时目录供测试改动(playwright/index.ts);pageWithUserData 则要求测试目录下存在 init-user-data,否则会直接抛错提示改用 page(playwright/index.ts)。

命名约定

  • 文件:*.spec.ts,用描述性名称(如 create-new-collection.spec.ts、sidebar-persistence.spec.ts);
  • 测试用例:清晰描述行为(如 should create a new collection);
  • 目录:按功能分组,同组 fixture 就近放置。

测试文件模板

import { test, expect } from '../../playwright';

test.describe('Feature Name', () => {
  test('should perform specific action', async ({ page }) => {
    // Arrange
    // Act
    // Assert
  });

  test('should handle error case', async ({ page }) => {
    // Test error scenarios
  });
});

仓库大量用例采用 test.describe 分组 + 语义化 test('should …') 命名的风格,如 tests/sidebar/rename-collection-item.spec.ts 等文件。

可用测试 Fixtures 详解

Bruno 的 Playwright 设置在 playwright/index.ts 中通过 baseTest.extend 声明了双层 fixture:

  • test 级 fixture(每个测试独立):context、page、newPage、pageWithUserData、collectionFixturePath、workspaceFixturePath、installFakeClipboard、restartApp;
  • worker 级 fixture(整个 worker 共享一次):createTmpDir、launchElectronApp、electronApp、reuseOrLaunchElectronApp。

Core Fixtures

Fixture 说明
page 主测试页面。会自动等待应用窗口真正就绪:内部调用 waitForReadyPage(playwright/index.ts),先尝试 app.firstWindow(),取不到则 waitForEvent('window'),再等待 [data-app-state="loaded"] 出现并额外等待 200ms;启用 trace 时自动附加 trace 文件到测试报告
context Browser context(来自 electronApp.context()),trace 开启时负责启动 tracing
electronApp worker 级共享的 Electron 应用实例,通过 launchElectronApp() 惰性创建

Utility Fixtures

Fixture 说明
createTmpDir(tag?) worker 级:用 fs.mkdtemp 在系统临时目录创建 pw-<tag>- 前缀的目录并跟踪记录,worker 结束时统一递归删除。tag 中 Windows 非法字符与空白会被替换为 -(playwright/index.ts)
newPage 新启动一个独立 Electron 应用并返回其首个就绪页面(与 page 隔离,适合多应用交互场景)
pageWithUserData 从测试同目录 init-user-data/ 拷贝初始用户数据到临时目录后启动应用;文件中的 {{projectRoot}} 等占位符会被替换,preferences.json 会用 lodash merge 与 defaultPreferences 合并(playwright/index.ts)
launchElectronApp(options?) worker 级:底层启动逻辑。选项支持 initUserDataPath(初始用户数据目录,逐文件做 {{var}} 模板替换)、userDataPath(自定义用户数据目录)、dotEnv(追加环境变量)、templateVars(模板变量)。启动时注入 ELECTRON_USER_DATA_PATH、DISABLE_SAMPLE_COLLECTION_IMPORT=true、PLAYWRIGHT=true、DISABLE_SINGLE_INSTANCE=true 等环境变量,并加 --disable-gpu 参数(playwright/index.ts)
reuseOrLaunchElectronApp(options?) worker 级:以 testFile/userDataPath/initUserDataPath 为 key 缓存应用实例;同一 key 复用,切换 key 或 closePrevious: true 时优雅关闭旧实例,避免资源累积
electronApp 快捷方式,等价于无参 launchElectronApp()
installFakeClipboard 在页面上用 JS 替身替换 navigator.clipboard,断言 “复制了什么内容”而不触碰并行 worker 共享的真实系统剪贴板;提供 copiedText() 读取最后一次复制内容(playwright/index.ts)

此外工具文件还导出 restartApp(复制当前测试的 init-user-data 后重启应用,常配合快照/持久化测试)与 closeElectronApp(多阶段、带超时的优雅关闭——先经主进程关闭全部 BrowserWindow 触发正常退出链,超时才 SIGKILL,避免 macOS Crash Reporter 弹窗,见 playwright/index.ts)。

使用 Fixtures

test('Test with multiple fixtures', async ({ page, createTmpDir, electronApp }) => {
  const testDir = await createTmpDir('test-data');

  // Your test logic here
});

需要与 Electron 主进程交互时(例如 mock dialog.showOpenDialog),在测试内解构 electronApp 后调用 electronApp.evaluate(...),参考 tests/utils/page/mounting.ts 中 openCollectionFromPath 的做法。

运行测试

基础命令

# 运行默认全部 E2E 测试(default + system-pac 两个 project)
npm run test:e2e

# 运行单个测试文件
npx playwright test tests/common/home-screen.spec.ts

# 运行某个目录下的测试
npx playwright test tests/folder-a/

注意根 package.json 提供多个细分入口:

npm run test:e2e:ssl        # 仅 ssl project(自定义 CA 证书相关)
npm run test:e2e:auth       # 仅 auth project(OAuth1/NTLM/Akamai EdgeGrid 等)
npm run test:e2e:mock-server # 仅 mock-server project
npm run test:e2e:sanity     # default + system-pac,仅跑带 @sanity 标签的用例

各 project 的划分与 testIgnore 规则定义在 playwright.config.ts:例如 ssl/**、auth/**、benchmarks/**、mock-server/** 在默认 project 中被排除,因为它们在各自独立 project 中运行,依赖独立端口/证书/服务。

高级选项

# UI 模式(可视化调试、步进)
npx playwright test --ui

# 有头模式(肉眼观察 Electron 窗口)
npx playwright test --headed

# 指定 project
npx playwright test --project="Bruno Electron App"

# 调试模式(配合 Inspector / Pause)
npx playwright test --debug

# 开启 trace 录制
npx playwright test --trace on

实际 project 名以 playwright.config.ts 为准(default、auth、ssl、system-pac、mock-server),默认 use.trace 在 CI 下为 on-first-retry、本地为 on;若要全局关闭可显式传 --trace off。

WebServer 自动启动

playwright.config.ts 声明了两个 webServer:

  1. npm run dev:web——启动前端开发服务器,等待 stdout 出现 ready built in 正则,超时 10 分钟;
  2. npm start --workspace=packages/bruno-tests——启动用于测试的本地 mock HTTP 服务,等待 http://localhost:8081/ping 可访问。

因此上面示例中使用的 http://localhost:8081/ping 请求目标就来自 packages/bruno-tests 工作区(如 packages/bruno-tests 下的 docker-compose/集合定义)。

最佳实践

1. 在 Page Module 中集中 Locator 与动作

绝不在 spec 中内联裸的 page.locator(...) / page.getByTestId(...)。Locator 及其交互全部放在 tests/utils/page/* 下的 page module 中,spec 通过共享的构建器与导出动作消费它们。这样选择器保持单一来源,UI 改动只需修一处。

一个 page module 只归属一个界面区块。tests/utils/page/mounting.ts 是参考样板:buildCollectionTreeLocators(page) 与其动作(waitForCollectionMount、openCollectionFromPath、getCollectionTreeStructure、getCollectionItemCount、waitForItemCount 等)同文件共存。

新功能区块 → 新建文件 → 并入 common。为新区块新建 page module(不要往 locators.ts 的内联对象里继续堆),再把它的 locator builder 挂进 buildCommonLocators(见 tests/utils/page/locators.ts 的聚合结构),spec 就能免费使用。这是每个新 page module 的硬性要求。

spec 中只构建一次 locator 并按需解构所需分组:

import { test, expect } from '../../playwright';
import { buildCommonLocators, createCollection, createRequest, closeAllCollections } from '../utils/page';

test('should rename a request via the sidebar', async ({ page, createTmpDir }) => {
  const { sidebar, actions, dropdown } = buildCommonLocators(page);
  const testDir = await createTmpDir('rename-test');

  await createCollection(page, 'My Collection', testDir);
  await createRequest(page, 'Test Request', 'My Collection');

  await sidebar.request('Test Request').hover();
  await actions.collectionItemActions('Test Request').click();
  await dropdown.item('Rename').click();

  await closeAllCollections(page);
});

新建一个 page module(locator builder 与动作同文件):

// tests/utils/page/notifications.ts — one file owns the "notifications" section
import { test, Page } from '../../../playwright';

export const buildNotificationLocators = (page: Page) => ({
  toast: (text: string) => page.getByTestId('notification-toast').filter({ hasText: text }),
  dismissButton: () => page.getByTestId('notification-dismiss')
});

export const dismissNotification = async (page: Page, text: string) => {
  await test.step(`Dismiss notification "${text}"`, async () => {
    const notifications = buildNotificationLocators(page);
    await notifications.toast(text).waitFor({ state: 'visible' });
    await notifications.dismissButton().click();
  });
};

随后把它挂进 buildCommonLocators 供所有 spec 使用:

// tests/utils/page/locators.ts
import { buildNotificationLocators } from './notifications';

export const buildCommonLocators = (page: Page) => ({
  runner: () => page.getByTestId('run-button'),
  sidebar: { /* … */ },
  notifications: buildNotificationLocators(page),   // now buildCommonLocators(page).notifications
  // …
});

约束范围:

  • 新测试严格:任何新 spec 都必须走此模式,禁止直接写选择器、禁止重复内联查询;
  • 存量测试宽松:对既有 spec 的小改动不必重构其选择器;但若大范围重写/实质性修改,则应在本次改动中把选择器与交互抽成 page module;
  • 暂不追溯改造既有模块:部分已抽取模块(如 tests/utils/page/mounting.ts)尚未并入 buildCommonLocators,保持现状即可——以上规则面向未来新增,不是一次强制迁移;
  • 长期目标:每个区块都成为 page module、每个 module 都能从 buildCommonLocators 触达,使 locator 与动作长期保持一致、单一来源。

仓库的实际组织与这一规范吻合:tests/utils/page/locators.ts 聚合了 sidebar、environment、modal、dropdown、tabs、response、timeline、websocket、aiAssist、varsPanel、grpc 等十余个构建器;tests/utils/page/actions.ts 则导出 closeAllCollections、createCollection、createRequest、createEnvironment、addEnvironmentVariable、openRenameModal、importCollection、removeCollection 等成套动作,动作内部统一以 test.step 包裹并以 waitFor 同步。

2. 使用语义化选择器

适用于 page module 内部(locators.ts 或区块文件)书写选择器,spec 层不直接写选择器。

推荐:

page.getByTestId('collection-name');
page.getByRole('button', { name: 'Create' });
page.getByLabel('Collection Name');

避免:

page.locator('.btn-primary');
page.locator('#collection-name');

仓库 UI 本身大量使用 data-testid(如 run-button、response-status-code、save-request-button、request-tab-close-icon、sidebar-collection-item-row 等,见 tests/utils/page/locators.ts),这些 stable id 就是首选锚点。

3. 保持 defaultPreferences 与应用偏好同步

E2E 启动会用一个全新的 userData 目录,其内容来自 playwright/index.ts 的 defaultPreferences mock(并与 init-user-data/preferences.json 以 lodash merge 合并,数组按下标合并而非拼接)。每当你在应用 preferences.json 的 schema/默认值中增删键,都要在此 mock 里同步一个默认值,否则测试将跑在未设置偏好的状态,偏离真实应用行为:

// playwright/index.ts
const defaultPreferences = {
  preferences: {
    onboarding: {
      hasLaunchedBefore: true,
      hasSeenWelcomeModal: true,
      lastSeenVersion: version
    },
    ai: {
      enabled: false   // 应用新增偏好键时,同步在此补默认值
    }
    // ← add the default for any new preferences.json key here
  }
};

version 直接从 packages/bruno-app/package.json 导入(playwright/index.ts),确保 mock 与应用版本一致。

4. 创建相互隔离的测试

每个测试彼此独立:自己的临时目录、自己的数据、确定性的清理动作。

import { test, expect } from '../../playwright';
import { buildCommonLocators, createCollection, closeAllCollections } from '../utils/page';

test('should create a collection', async ({ page, createTmpDir }) => {
  const { sidebar } = buildCommonLocators(page);
  const testDir = await createTmpDir('collection-test');   // isolated per test

  await createCollection(page, 'test-collection', testDir);
  await expect(sidebar.collection('test-collection')).toBeVisible();

  await closeAllCollections(page);   // deterministic cleanup
});

closeAllCollections(tests/utils/page/actions.ts)是清理侧边栏所有集合的现成动作,会处理 “普通移除”与 “含草稿需 Discard All and Remove”两种弹窗,并最终断言集合数为 0。

5. 添加有意义的断言

始终通过 page module 的 locator 校验期望结果:

import { test, expect } from '../../playwright';
import { buildCommonLocators, createCollection, createRequest, saveRequest, closeAllCollections } from '../utils/page';

test('should save a request', async ({ page, createTmpDir }) => {
  const { tabs } = buildCommonLocators(page);
  const testDir = await createTmpDir('save-test');

  // Arrange
  await createCollection(page, 'Save Test', testDir);
  await createRequest(page, 'Get Ping', 'Save Test', { url: 'http://localhost:8081/ping', method: 'GET' });

  // Act
  await saveRequest(page);

  // Assert — the tab is open and no longer shows the unsaved-changes indicator
  await expect(tabs.requestTab('Get Ping')).toBeVisible();
  await expect(tabs.draftIndicator()).toBeHidden();

  await closeAllCollections(page);
});

6. 断言留在 spec,动作不做断言

expect(...) 属于 spec——测试意图与判定标准必须在那里可见。tests/utils/page/* 中的动作辅助函数负责执行交互并同步状态,不得断言测试期望,否则会把通过/失败逻辑藏进可复用 helper,并强迫所有调用方接受同一种期望。

动作用 waitFor 同步;spec 用 expect 校验。 当动作需要等 UI 到达某状态再走下一步(弹窗打开、加载条消失),用 locator.waitFor({ state })、page.waitForLoadState() 等 Playwright 等待原语,而不是 expect——waitFor 保证下一步动作可靠,expect 决定用例是否通过并只应出现在 spec 中:

// tests/utils/page/collection.ts — the action WAITS, it does not assert
export const openRenameModal = async (page: Page, requestName: string) => {
  await test.step(`Open rename modal for "${requestName}"`, async () => {
    const { sidebar, actions, dropdown } = buildCommonLocators(page);
    await sidebar.request(requestName).hover();
    await actions.collectionItemActions(requestName).click();
    await dropdown.item('Rename').click();
    // Synchronization, not assertion — wait until the modal is ready to interact with
    await page.locator('.bruno-modal').filter({ hasText: 'Rename Request' }).waitFor({ state: 'visible' });
  });
};
// the spec OWNS the assertion
test('renames a request', async ({ page, createTmpDir }) => {
  const { modal } = buildCommonLocators(page);
  // … arrange: create collection + request …

  await openRenameModal(page, 'Test Request');

  await expect(modal.title('Rename Request')).toBeVisible();   // expect lives here, in the spec
});

7. 处理异步操作

优先使用自动重试断言与封装了等待的动作 helper,绝不等待裸内联选择器:

import { test, expect } from '../../playwright';
import { buildCommonLocators, sendRequestAndWaitForResponse } from '../utils/page';

test('should wait for async operations', async ({ page }) => {
  const { response } = buildCommonLocators(page);

  // Action helpers wrap "do the thing + wait for its result"
  await sendRequestAndWaitForResponse(page, 200);

  // Auto-retrying assertions wait until the condition holds — no hardcoded sleeps
  await expect(response.statusCode()).toContainText('200');
  await expect(response.pane()).toBeVisible();

  // page.waitForResponse targets the network (not the DOM), so it's fine to use directly.
  // Avoid page.waitForSelector('[data-testid="…"]') — wait on a locator from a page module instead.
});

仓库中这类 “动作即同步” 的典型还包括 createCollection 提交后等弹窗关闭、等侧边栏集合名出现(tests/utils/page/actions.ts),以及 waitForCollectionMount 等待加载 spinner 消失后再断言树结构(tests/utils/page/mounting.ts)。

8. 测试数据管理

先写数据文件到临时目录,再从 page module 取动作与 locator:

import { test, expect } from '../../playwright';
import { buildCommonLocators, openCollection } from '../utils/page';

test('should work with test data', async ({ page, createTmpDir }) => {
  const { sidebar } = buildCommonLocators(page);
  const testDir = await createTmpDir('test-data');

  // Create test files
  await fs.writeFile(path.join(testDir, 'test.bru'), testContent);

  // Use in test — actions/locators come from page modules, not raw selectors
  await openCollection(page, 'test-data');
  await expect(sidebar.collection('test-data')).toBeVisible();
});

若希望把仓库内的夹具数据原样引入(fixtures/collection、fixtures/collections、fixtures/workspace),可直接解构 collectionFixturePath / workspaceFixturePath(见 playwright/index.ts),它们已帮你完成拷贝到临时目录与路径正斜杠规范化。

完整示例

以下示例均使用 buildCommonLocators 提供 locator、使用 tests/utils/page 导出的动作 helper(依据见 Best Practices §1)。

示例 1:基本集合创建

import { test, expect } from '../../playwright';
import { buildCommonLocators, createCollection, closeAllCollections } from '../utils/page';

test('should create a new collection', async ({ page, createTmpDir }) => {
  const { sidebar } = buildCommonLocators(page);
  const testDir = await createTmpDir('new-collection');

  await createCollection(page, 'My Test Collection', testDir);

  await expect(sidebar.collection('My Test Collection')).toBeVisible();
  await closeAllCollections(page);
});

示例 2:创建并执行请求

import { test, expect } from '../../playwright';
import {
  buildCommonLocators,
  createCollection,
  createRequest,
  sendRequestAndWaitForResponse,
  closeAllCollections
} from '../utils/page';

test('should create and execute an HTTP request', async ({ page, createTmpDir }) => {
  const { response } = buildCommonLocators(page);
  const testDir = await createTmpDir('request-test');

  await createCollection(page, 'Request Test', testDir);
  await createRequest(page, 'Ping', 'Request Test', {
    url: 'http://localhost:8081/ping',
    method: 'GET'
  });

  // Sends the active request and asserts the status code in one step
  await sendRequestAndWaitForResponse(page, 200);

  await expect(response.statusCode()).toContainText('200');
  await closeAllCollections(page);
});

示例 3:环境变量管理

import { test, expect } from '../../playwright';
import {
  buildCommonLocators,
  createCollection,
  createEnvironment,
  addEnvironmentVariable,
  closeAllCollections
} from '../utils/page';

test('should create and use environment variables', async ({ page, createTmpDir }) => {
  const { environment } = buildCommonLocators(page);
  const testDir = await createTmpDir('env-test');

  await createCollection(page, 'Environment Test', testDir);

  await createEnvironment(page, 'Development');
  await addEnvironmentVariable(page, { name: 'API_URL', value: 'http://localhost:3000' });

  await expect(environment.varRow('API_URL')).toBeVisible();
  await closeAllCollections(page);
});

故障排查(Troubleshooting)

常见问题

1. Electron 应用无法启动

# 确认依赖已安装
npm install

# 先手动启动应用验证
npm run dev:electron

若仍失败,可尝试 npm run dev:electron:debug(对应 Electron 工作区 debug 脚本)。应用层面的启动就绪信号是 [data-app-state="loaded"],测试等待该节点出现(最长 45 秒,playwright/index.ts)。

2. 测试超时

先找出 为什么 慢——超时通常是症状而非问题本身。把硬编码等待替换为自动重试断言、等待应用就绪信号([data-app-state="loaded"]),并使用会等待自身结果的动作 helper。单纯调大超时只会掩盖真问题并拖慢整个测试套件。

仅当用例确实在做长耗时工作(大型导入、访问真实慢端点)时才提高超时——并且只对该测试生效,而不是全局:

// Justified: this test imports a very large collection that legitimately takes ~40s.
test('imports a large collection', async ({ page }) => {
  test.setTimeout(60000); // 60s — the work is genuinely long, not a masked flake
  // Test steps
});

3. 元素找不到

// Wait for element to be present
await page.waitForSelector('[data-testid="element"]');

// Or use more specific selectors
await page.getByRole('button', { name: 'Exact Button Text' }).click();

更推荐把等待收进 page module 动作,用 locator.waitFor({ state: 'visible' }) 等可见状态再交互。

4. 用例不稳定(Flaky)

// Use stable selectors
await page.getByTestId('stable-id').click();

// Wait for state changes
await page.waitForLoadState('networkidle');

优先使用语义化/data-testid 锚点(见 Best Practices §2),依赖网络或复杂动画时明确等待对应状态。另外可利用 expect(...).toPass({ timeout }) 把易竞态的多步期望包成可重试块——仓库在 hover 后菜单需短暂出现等场景大量使用该技巧(参考 tests/utils/page/actions.ts)。

调试模式

# 调试运行(进入 Inspector/Pause)
npx playwright test --debug

# 调试单个测试文件
npx playwright test --debug tests/common/home-screen.spec.ts

本地开发还可用 npx playwright test --ui 以 UI 模式单步回放;需要肉眼看 Electron 窗口行为时用 --headed。

Trace 分析

# 运行并录制 trace(本地默认即开启,也可显式指定)
npx playwright test --trace on

# 在浏览器中查看 trace
npx playwright show-trace test-results/trace-*.zip

自定义 fixtures 对 trace 做了完善处理:context/page fixture 在 trace 开启时用 context.tracing.start(TRACING_OPTIONS)(截图+快照+源码)并以 chunk 方式把每次测试的 trace 写入 testInfo.outputPath() 并通过 testInfo.attach 挂到报告上(playwright/index.ts);CI 下配置默认 on-first-retry,即失败重试那次才有 trace。

配置文件说明

实际配置位于 playwright.config.ts,要点如下(文档正文为保证可读略作精简,实际以仓库为准):

export default defineConfig({
  fullyParallel: true,
  forbidOnly: !!process.env.CI,
  retries: process.env.CI ? 2 : 0,
  workers: undefined,

  use: {
    trace: process.env.CI ? 'on-first-retry' : 'on'
  },

  projects: [
    { name: 'default', testDir: './tests', testIgnore: ['ssl/**', 'auth/**', 'benchmarks/**', 'proxy/system-pac/**', 'mock-server/**'] },
    { name: 'auth', testDir: './tests/auth' },
    { name: 'ssl', testDir: './tests/ssl' },
    { name: 'system-pac', testDir: './tests/proxy/system-pac' },
    { name: 'mock-server', testDir: './tests/mock-server' }
  ],

  webServer: [
    { command: 'npm run dev:web', stdout: 'pipe', wait: { stdout: /ready\s+built in/i }, reuseExistingServer: !process.env.CI, timeout: 10 * 60 * 1000 },
    { command: 'npm start --workspace=packages/bruno-tests', url: 'http://localhost:8081/ping', reuseExistingServer: !process.env.CI, timeout: 10 * 60 * 1000 }
  ]
});

理解要点:

  • 大量用例默认全并行(fullyParallel: true);每个 spec 文件内如有串行需求,可在文件内用 test.describe.configure({ mode: 'serial' }) 控制;
  • CI 下重试 2 次、禁止 .only,并使用 list/html/json 报告器,CI 额外启用 github 与可跨分片合并的 blob 报告器;
  • projects 按“共享端口 / 独立服务”划分(如 system-pac 与 pac 共用端口、auth/ssl/mock-server 各有独立运行前提),跨 project 跑测试用根 package.json 里各自的 test:e2e:* 脚本即可。

其他相关资源

登录后查看全文
bruno