测试

离屏渲染,模拟按键,并断言帧文本。

本章应用正在你的控制台中运行。按 ⌘⌥JCtrl+Shift+J⌘⌥KCtrl+Shift+K⌘⌥C 打开控制台(先开启开发者功能),然后试用。
观看本章3:14

本章内容

  • 第一个测试
  • 模拟按键
  • 运行测试
  • 快照

@textjs/app/testing 离屏渲染应用,模拟按键,并以纯文本返回帧。测试无需浏览器或 DevTools 即可运行。

第一个测试

app/deployments/page.test.tsx+19tsx
新增:import { afterEach, beforeEach, expect, mock, spyOn, test } from "bun:test";新增:import { cleanup, render } from "@textjs/app/testing";新增:import { DEPLOYMENTS } from "../../lib/deployments";新增:import DeploymentsPage from "./page";新增:新增:beforeEach(() => {新增:  spyOn(globalThis, "fetch").mockResolvedValue(Response.json(DEPLOYMENTS));新增:});新增:新增:afterEach(() => {新增:  mock.restore();新增:  return cleanup();新增:});新增:新增:test("lists every deployment", async () => {新增:  const app = await render(<DeploymentsPage />, { cols: 80, rows: 12 });新增:  await app.waitForText("feat: stream cells downward");新增:  expect(app.lines()).toHaveLength(12);新增:});

页面从 /api/deployments 获取数据,但 bun test 下没有服务器,因此 beforeEach 用相同的数据为 fetch 设置桩。render 默认使用 80×24 的网格。lastFrame() 以文本返回整帧,lines() 逐行返回帧内容,cell(x, y) 则返回单个单元格的字符和颜色。

模拟按键

press 接受与 useKeymap 相同的按键字符串。每次调用都在 act() 内运行,并刷新产生的帧,因此下一条断言能看到更新。

app/deployments/page.test.tsx+14tsx
新增:test("↓ moves the highlight", async () => {新增:  const app = await render(<DeploymentsPage />);新增:  await app.waitForText("feat: stream cells downward");新增:  await app.press("down");新增:  const row = app.lines().find((line) => line.includes("›"));新增:  expect(row).toContain("perf: merge spans across rows");新增:});新增:新增:test("4 sorts by build time", async () => {新增:  const app = await render(<DeploymentsPage />);新增:  await app.waitForText("Build");新增:  await app.press("4"); // sort by the 4th column新增:  expect(app.locate("12s")?.y).toBeLessThan(app.locate("52s")?.y ?? 0);新增:});

表格在高亮行前绘制 ›,因此 ↓ 测试会找到该行并检查对应的提交。数字键按列排序,第四列是构建时间。

运行测试

bun test

任何支持 async 测试的运行器都能使用它:Bun、Vitest 或 Jest。在控制台中,按 Enter 运行测试套件,按 f 使一个测试失败,查看失败时的表现。

快照

toAnsi() 以真彩色 ANSI 格式返回帧,生成的快照也能捕获颜色回归:

expect(app.toAnsi()).toMatchSnapshot();

试用

这是本章结束时的 Acme Deploys,正在 DevTools 中运行。点击输入区,然后使用下列按键。

▼ 08 · 测试

打开控制台

⌘⌥J
CtrlShiftJ
⌘⌥K
CtrlShiftK
⌘⌥C

应用在 DevTools 中渲染。先在 Safari 设置 → 高级中开启“显示网页开发者功能”。 然后点击这里并按 Enter。

在桌面端打开

此应用在 DevTools 控制台中渲染,需要桌面浏览器。

测验

2 个问题

回答所有问题以完成本章。

运行 @textjs/app/testing 需要什么?

 

app.lastFrame() 返回什么?