端到端测试
acdev test 在真的运行时里测你的应用: 每个测试一个全新的、隔离的 acdev dev 开发会话, 用和 Playwright 相似的 API 找元素、点击、输入、断言、截图比对. 需要 Bun, 工程本身跑在 Node.js 上时也一样.
第一个测试
第一个测试 一节的链接测试文件叫 *.e2e.ts (也可以是 .tsx、.js、.mjs、.mts), 放在工程里任何地方:
import { test, expect } from 'acdev/test'
test('adds a task', async ({ app }) => { await app!.getByRole('textbox', { name: 'New task' }).fill('Buy milk') await app!.getByRole('button', { name: 'Add' }).click() await expect(app!.getByRole('listitem')).toHaveCount(1)})
test('starts empty again', async ({ app }) => { await expect(app!.getByRole('listitem')).toHaveCount(0)})acdev test普通的 bun test 不会匹配 *.e2e.*, 所以单元测试和 e2e 测试互不干扰. acdev/test 和 acdev/driver 由 acdev test 解析到正在运行的那个 acdev, 工程不需要装依赖.
夹具
夹具 一节的链接测试函数收到:
| 名字 | 是什么 |
|---|---|
app |
应用工程时是它的窗口 (AppWindow); 桌面工程时是 null |
acdev |
整个会话 (Acde): 打开应用、截屏、模拟、伪造请求…… |
home |
这个测试的临时 HOME |
settings |
本次运行的设置 |
隔离
隔离 一节的链接每个测试:
- 临时的
HOME和XDG_*目录, 存储只在内存; - 屏幕 1280 × 800, 浅色, 不跑自启动项;
- 默认 headless (
--headed开窗口看), 每个测试 60 秒超时 (--timeout); 会话启动花的时间也算在内. 在没有 GPU 的 Linux CI 上, 运行时通过软件 Vulkan 驱动 (lavapipe) 在 CPU 上绘制, 这个驱动必须装上, 而且很慢; 见 平台支持.
构建在 .acde/test, 结果在 .acde/test-results.
测试的会话不算工程的 acdev dev: 测试在跑时你对同一个工程运行的 acdev dev 照常启动、一直跑着, acdev eval 这样的命令和 MCP 工具用的是你的会话, 绝不用测试的 (只有 --session <pid> 能连到测试的会话).
找元素
找元素 一节的链接和 Playwright 一样的定位方式, 在语义树 (无障碍树) 上找:
app.getByRole('button', { name: '保存' })app.getByText('已保存')app.getByLabel('邮箱')app.getByPlaceholder('搜索')app.getByTitle('关闭')app.getByAltText('头像')app.getByTestId('submit') // data-testidapp.locator('ul.tasks > li') // CSS 选择器app.getByRole('listitem').filter({ hasText: '牛奶' }).first()app.getByRole('listitem').filter({ has: app.getByRole('checkbox', { checked: true }) })app.getByRole('button', { name: '保存' }).or(app.getByRole('button', { name: '重试' }))app.locator('li').and(app.getByText('牛奶'))Locator 是惰性的: 每次用到时在最新的树上重新找. 动作要求恰好一个匹配, 多个会报错而不是猜.
同一个元素里相邻的文字按原样连成一个名字: JSX 的 {rate}% 是 100%.
单独跑的应用在标题栏上显示窗口菜单 (窗口), 它们也在树里: 先点菜单, 再点那一项.
await app.getByRole('menuitem', { name: '文件' }).click()await app.getByRole('menuitem', { name: '新建' }).click()await app.keyboard.press('Control+N') // 一项的快捷键也能跑它filter 接受 hasText、hasNotText、has 和 hasNot (另一个 Locator, 在每个元素里面找). or 匹配两个 Locator 中任何一个匹配到的元素, 按文档顺序; and 匹配两个都匹配到的元素.
按 CSS 找的 Locator (locator、getByTestId、getByPlaceholder ……) 也匹配没有渲染出来的元素, 和 Playwright 一样: toHaveCount 把它们算在内, toBeVisible / toBeHidden / isVisible() / waitFor({ state }) 判断元素有没有渲染出来, 动作会等到它渲染出来. 通过语义树找到的元素 (getByRole、getByText、getByLabel) 总是渲染出来的.
动作
动作 一节的链接await locator.click()await locator.dblclick()await locator.hover()await locator.fill('文字') // 替换await locator.type('文字') // 追加await locator.clear()await locator.press('ctrl+a backspace') // 键名: 见调试工具的「键名」await locator.selectOption('beta')await locator.check() / uncheck() / setChecked(true)await locator.dragTo(other)await locator.scroll(400)click、fill 等会等元素可用 (不是 disabled), 失败时重试到超时. press 接受的键列在 键名 里.
click、dblclick 和 hover 接受 modifiers, 即动作期间按住的键: Shift、Control、Alt、Meta 或 ControlOrMeta; ControlOrMeta 在每个系统上都是 Control, 因为页面在哪里看到的都是 Linux 环境 (见 Web 兼容性).
await locator.click({ modifiers: ['Shift'] })const size = await locator.evaluate((element, unit) => element.getBoundingClientRect().width + unit, 'px')locator.evaluate(fn, arg) 在页面里用这个元素和一个 JSON 参数调用一个函数, 返回它的 JSON 结果.
不针对某一个元素的输入, 用 app.mouse 和 app.keyboard, 它们按页面坐标发原始事件 (CSS 像素, 就是 getBoundingClientRect() 给出的那种):
await app.mouse.move(40, 120)await app.mouse.down()await app.mouse.move(240, 120, { steps: 8 }) // 拖动, 分八次移动, 每次隔一帧await app.mouse.up()await app.mouse.click(300, 200, { button: 'right' })await app.mouse.wheel(0, 400)
await app.keyboard.press('Control+a')await app.keyboard.type('Hello') // 按键; 没有对应按键的字符作为文字输入await app.keyboard.insertText('你好') // 像输入法提交文字那样await app.keyboard.down('Shift')await app.keyboard.up('Shift')断言
断言 一节的链接await expect(locator).toBeVisible()await expect(locator).toHaveText('完成')await expect(locator).toContainText('完成')await expect(locator).toHaveValue('42')await expect(locator).toHaveCount(3)await expect(locator).toBeChecked()await expect(locator).toBeDisabled()await expect(locator).toBeFocused()await expect(locator).toHaveAttribute('aria-expanded', 'true')await expect(locator).not.toBeVisible()
await expect(locator).toHaveClass(/active/)await expect(locator).toHaveCSS('color', 'rgb(255, 0, 0)') // 计算后的样式await expect(locator).toHaveJSProperty('checked', true)await expect(locator).toBeEmpty()await expect(locator).toBeEditable()await expect(locator).toBeInViewport({ ratio: 0.5 })
await expect(app).toHaveTitle('笔记')await expect(app).toBeOpen()toHaveText 和 toContainText 比较的是元素的文本内容, 和 Playwright 一样: 元素里面的文字, 空白合并, 不是它的无障碍名字. <output aria-label="Display">18</output> 的文本是 18; getByText、getByRole(…, { name }) 这类定位匹配的是无障碍名字 (Display). locator.textContent() 读文本内容, locator.name() 读无障碍名字.
UI 断言会重试到超时 (默认 5 秒). 别的值用 expect 时就是 bun:test 的 expect.
expect.poll 对测试自己读出来的值重试一个 bun:test 的 matcher, 直到它通过或超时. expect.soft 记下失败, 让测试继续跑; 测试在结束时失败, 并列出每一个 soft 失败.
await expect.poll(() => app.evaluate<number>('window.saved'), { timeout: 2000 }).toBe(3)await expect.soft(app.getByRole('heading')).toHaveText('Notes')expect.soft(total).toBe(42)截图比对
截图比对 一节的链接await expect(app).toHaveScreenshot()await expect(app.getByRole('textbox')).toHaveScreenshot('field', { maxDiffPixels: 20, mask: [app.getByTestId('clock')] })- 基线在测试文件旁的
__screenshots__/<文件名>/<名字>-<平台>.png. 没有基线时写一张; 设了CI环境变量时报错. - 连拍到两张一样才比较; 不一样就重拍到超时.
- 不通过时
-actual、-expected、-diff三张图写进结果目录. acdev test -u重写基线.- 选项:
maxDiffPixels、maxDiffPixelRatio、threshold(默认 0.2)、mask、timeout.
网络、文件选择器、剪贴板
网络、文件选择器、剪贴板 一节的链接// 伪造回应await app.route('/api/todos', { json: [{ id: 1, title: 'mocked' }] })await app.route('**/avatar.png', { abort: true })
// 等请求或日志 (先调用, 再触发)const request = app.waitForRequest('/api/save', { method: 'POST' })await app.getByRole('button', { name: '保存' }).click()await request
// 事先回答文件选择器 (null: 当作用户取消了)await acde.chooseFiles(['/tmp/a.txt'])await acde.chooseFolder('/tmp/project')await acde.chooseSaveFile('/tmp/out.md')await app.getByRole('button', { name: 'Open folder' }).click()
// 深色模式await acde.emulate({ colorScheme: 'dark' })
// 剪贴板 (headless 下是会话自己的)await acde.setClipboard('hello')除非 acdev test --headed, 测试都是 headless 跑的, 而 headless 会话不显示选择器对话框: 页面打开的选择器没有事先给的回答就会失败, 页面看到的是被取消了. 所以要在打开选择器的那个动作之前调 chooseFolder、chooseFiles 或 chooseSaveFile; 每个回答给同一种选择器的下一次.
要检查样式或盒子, 在页面里求值: await app.locator('h1').evaluate((element) => getComputedStyle(element).color), 或者像 动作 里那样用 getBoundingClientRect().
时间、对话框和页面准备
时间、对话框和页面准备 一节的链接app.clock 接管页面的时间, 所以测定时器的测试不用等它到时间:
await app.clock.install({ time: '2026-01-01T09:00:00Z' }) // Date、performance.now、定时器和动画帧await app.clock.fastForward('25:00') // 往前跳; 每个到期的定时器触发一次await app.clock.runFor(1000) // 一步步往前走; 每个定时器在它自己的时刻触发await app.clock.pauseAt('2026-01-01T10:00:00Z')await app.clock.resume()await app.clock.setFixedTime(0) // Date 停住不动; 定时器照常走await app.clock.setSystemTime('2030-06-01') // 只改 Date时刻是 1970 年以来的毫秒数、Date 或日期字符串; 时长是毫秒数、"mm:ss" 或 "hh:mm:ss". 装上的时钟一直留到页面重新载入. CSS 动画和过渡仍然按真实时间走.
acdev runtime 没有让用户点的对话框: alert 画在窗口里, confirm 回 false, prompt 回 null. 测试事先回答下一个对话框:
await app.answerDialog({ accept: true }) // 下一个 confirm 回 trueawait app.answerDialog({ text: 'Untitled' }) // 下一个 prompt 回这段文字const shown = app.waitForDialog({ type: 'confirm' }) // 先调用, 再触发await app.getByRole('button', { name: 'Delete' }).click()expect((await shown).message).toBe('Delete this note?')await app.dialogs() // 页面弹过的每个对话框, 以及它是怎么回答的让测试从一个准备好的页面开始:
test('opens the saved draft', { size: [480, 640], localStorage: { draft: 'Hello' } }, async ({ app }) => { await expect(app!.getByRole('textbox')).toHaveValue('Hello')})选项放在第二个或第三个参数 (test(name, options, body) 或 test(name, body, options)): timeout、size (页面的宽和高) 和 localStorage (在页面载入之前写入). 它们做的事和测试里的这些调用一样:
await app.seedLocalStorage({ draft: 'Hello' }) // 写入这些条目, 再重新载入页面await app.resize(480, 640) // 页面的尺寸, 不含标题栏await app.addInitScript('window.testing = true') // 每次载入时, 在页面自己的脚本之前运行await app.reload()size 和 localStorage 需要 app 夹具, 所以它们在应用工程里能用, 带 --desktop 时不能用.
批准
批准 一节的链接声明了的能力不用回答. 只有摄像头和麦克风会问用户 (见 系统能力), 在页面第一次调 getUserMedia() 时; 还有空闲检测 (idleDetection, 在页面调用 IdleDetector.requestPermission() 时). 每个测试的 home 一开始都是空的, 所以什么都还没决定, 也没有哪个提示会自己得到回答: 这次调用一直等到测试回答:
import { expect, test } from 'acdev/test'
test('records once the user allows the microphone', async ({ app, acdev }) => { await app!.getByRole('button', { name: 'Record' }).click() await acde.allow({ capability: 'microphone' }) await expect(app!.getByText('Recording')).toBeVisible()})acde.allow() 和 acde.deny() 等一个匹配的提示 ({ app, capability }, 两项都可以不给) 并回答它; acde.permissions() 列出在等的提示和已做的决定; acde.revoke(app, capability) 收回一个决定. 要测用户说不时应用怎么表现, 就 deny 掉这个提示: 这时 getUserMedia() 以 NotAllowedError reject.
失败时
失败时 一节的链接失败的测试在 .acde/test-results/<文件>/<测试>/ 留下:
error.txt output.log screen.png snapshot.txt console.txt network.txt trace.txt
超时的测试以 TimeoutError: the test did not finish within <ms> ms (its timeout: --timeout, or the one given to test()) 失败, 留下同样的文件, 内容取自超时的那一刻.
会话没起来的测试没有屏幕可存: 它留下 error.txt 和 output.log, 后者是这个测试的 acdev dev 的全部输出. 错误先说明启动走到了哪一步, 再引用这份输出的最后 40 行 (启动不了的应用在那里说明原因, 比如 Notes needs "clock" (service not running)):
| 错误的开头 | 发生了什么 |
|---|---|
acdev dev exited (<code>) before it was ready: |
acdev dev 以这个退出码结束: 构建失败, 或 acdev runtime 拒绝了这个应用 |
acdev dev (pid <pid>) did not register a session within <n> s in <dir>, 接着是 no session yet: its build did not finish, or acdev runtime did not start listening; last output: |
构建或 acdev runtime 的启动花的时间超出了测试的超时允许的时间 |
acdev dev did not start within <n> s:, 接着是 acdev runtime runs and answers, but no window appeared (pages: 0, windows: 0) and no approval prompt waits; last output: |
acdev runtime 在跑, 但应用没有开窗口 |
--trace 时每个测试都留一份 trace.html: 每一步动作和断言、耗时、结果, 每步之后的整屏截图.
--video 时失败的测试还留下 video.png, 一张屏幕的动画 PNG (每秒四帧, 留最后 600 张有变化的帧); --video=on 给每个测试都留一份. --retries 时目录里是最后一次尝试留下的东西.
命令
命令 一节的链接acdev test # 工程里所有 *.e2e.*acdev test e2e/tasks.e2e.ts # 指定文件acdev test -t "adds" # 只跑名字匹配这个正则表达式的测试acdev test --headed # 开窗口看acdev test --desktop dopame # 应用跑在 dopame 桌面里acdev test --bail --timeout 30000acdev test --traceacdev test -u # 更新截图基线acdev test --workers 2 # 一次跑两个文件acdev test --retries 1 --video # 失败的测试再跑一次; 给失败的测试留一份录像几个文件同时跑: 数量是机器核数的一半, 最多 4 个, 带 --headed 或 --bail 时一次一个 (--workers 设这个数). 每个 worker 构建到它自己的目录 (.acde/test、.acde/test-2 ……). 失败的测试会再跑 --retries 次, 每次都在全新的会话上, 有它自己的超时; 后面有一次尝试通过, 测试就通过, 并有一行写着 passed on attempt 2 of 2 (flaky).
用 -t 时, 没有测试匹配的文件会被跳过, 也不算失败 (acdev test: e2e/approval.e2e.ts: no test matches -t "saves", skipped); 所有文件里都没有测试匹配时, acdev test 打出 acdev test: no test matches -t "<pattern>" in <n> files, 退出码 1.
每个文件跑的时候打出它自己那次 bun test 的输出; 几个文件同时跑时, 一个文件的输出在它跑完时整块打出. 整次运行以一行汇总结束:
acdev test: 5 tests in 2 files: 4 passed, 1 failed, 1 not run (skipped, todo, or not matched by -t); failed: e2e/notes.e2e.ts what the failing tests left: /path/to/notes/.acde/test-results- 它数的是跑过的文件里的测试: 跑了多少、在几个文件里、通过多少、失败多少, 以及 (有的话) 多少没跑 (
test.skip、test.todo, 以及被-t排除的测试). 这些数字来自bun test给每个文件写的报告. failed:列出有失败测试的文件 (一个文件里的测试全都通过, 这个文件才算通过). 没留下报告的文件 (它没能载入, 或它那次运行被杀掉了) 不计数, 只列出名字:; not counted: e2e/broken.e2e.ts (bun test left no report: the file did not load, or its run was killed). 适用时还加上; <n> files skipped (no test matches -t)和; <n> files not run (--bail). 有失败的测试留下了文件时, 它下面才有缩进的那一行.
没有失败时退出码是 0, 否则是 1. 还没有端到端测试的工程 (新建的工程) 不算失败: acdev test 会说明这一点, 指向这一页, 以退出码 0 退出.
编辑器里的类型
编辑器里的类型 一节的链接acdev/test 导出它交给你的每样东西的类型, 所以辅助函数可以标上类型: Fixtures (测试函数的参数)、AppWindow (app 夹具)、Locator、Acde, 以及 测试 API 里列出的选项和结果的类型.
import { test, expect, type AppWindow, type Locator } from 'acdev/test'
async function enter(app: AppWindow, keys: string[]): Promise<Locator> { for (const key of keys) await app.getByRole('button', { name: key }).click() return app.locator('#display')}
test('adds', async ({ app }) => { await expect(await enter(app!, ['1', '+', '2', '='])).toHaveText('3')})acdev test 运行时自己解析 acdev/test, 但编辑器不知道它在哪. 现在需要在工程的 tsconfig.json 里加 paths, 指向安装目录里的类型声明, 写主目录的绝对路径 (tsconfig.json 不展开 ~ 和 %USERPROFILE%):
{ "compilerOptions": { "skipLibCheck": true, "paths": { "acdev/test": ["/home/me/.acdev/current/lib/acdev/dist/types/e2e/index.d.ts"], "acdev/driver": ["/home/me/.acdev/current/lib/acdev/dist/types/driver/index.d.ts"] // Windows: "C:/Users/me/.acdev/current/lib/acdev/dist/types/e2e/index.d.ts" } }}acdev test 读的是同一份 paths, 并把这两项换成它自己的, 所以它们不改变测试怎么跑. 以后会有单独的类型包.
单独用 driver
单独用 driver 一节的链接acdev/driver 也能在任何 Node.js / Bun 脚本里用. 在 acdev test 之外没有东西替你解析 acdev/driver: 把装好的 acdev link 进脚本所在的工程一次 (它是一个叫 acdev 的包, 类型也在里面):
cd ~/.acdev/current/lib/acdev && bun link # 用 Node.js 时 npm linkcd ~/my-scripts && bun link acdev # npm link acdevlink 指向的是现在装的这个版本; 升级 acdev 之后要再 link 一次.
import { Acde } from 'acdev/driver'
const acdev = await Acde.launch({ dirs: ['./my-app'], headless: true })await acde.open('notes')await acde.window('notes').getByRole('button', { name: '新建' }).click()await acde.close()Acde.attach() 连到一个已经在跑的 acdev dev 开发会话. 完整 API 见 参考: 测试 API.