测试
测试原语的交互、无障碍属性、服务端输出和阅读方向。
@ui-sdk/core/testing 提供辅助函数,用来模拟输入、检查焦点和无障碍属性,并查看原语的状态和服务端输出。
你可以用它们直接测试原语,或检查渲染后的组件。交互测试需要一个 DOM,比如 jsdom 或浏览器。服务端输出和部件读取不需要 DOM。
检查模式
如果你渲染的控件遵循常见的无障碍模式,checkPattern 会检查它的角色、名称、状态、部件之间的引用和键盘交互:
import { checkPattern } from "@ui-sdk/core/testing"
await checkPattern(root, "tabs")root 是控件的元素,或包围它的元素。检查会抛出包含所有问题的单个错误。在这里,移除选项卡列表的名称就能让它有东西可报告:
import * as React from "react"
import { checkPattern } from "@ui-sdk/core/testing"
import { Tabs, TabsList, TabsPanel, TabsTab } from "./tabs"
function Example() {
const root = React.useRef<HTMLDivElement>(null)
const [named, setNamed] = React.useState(true)
const [result, setResult] = React.useState<{
ok: boolean
text: string
} | null>(null)
async function check() {
setResult(null)
try {
await checkPattern(root.current!, "tabs")
setResult({
ok: true,
text: "Passes: roles, states, names, one tab stop, the arrows, Home and End.",
})
} catch (error) {
setResult({ ok: false, text: (error as Error).message })
}
}
return (
<div data-slot="check">
<div data-slot="controls">
<button type="button" data-variant="solid" onClick={check}>
Check the Tabs Pattern
</button>
<label data-slot="label">
<input
type="checkbox"
checked={!named}
onChange={(event) => {
setNamed(!event.target.checked)
setResult(null)
}}
/>
Leave the tab list unnamed
</label>
</div>
<Tabs ref={root} defaultValue="overview">
<TabsList aria-label={named ? "Project" : undefined}>
<TabsTab value="overview">Overview</TabsTab>
<TabsTab value="activity">Activity</TabsTab>
<TabsTab value="files">Files</TabsTab>
</TabsList>
<TabsPanel value="overview">
The project plan and upcoming milestones.
</TabsPanel>
<TabsPanel value="activity">
Recent updates from the project team.
</TabsPanel>
<TabsPanel value="files">
Briefs, mockups and other project files.
</TabsPanel>
</Tabs>
{result && (
<p
role="status"
data-slot="check-result"
data-status={result.ok ? "pass" : "fail"}
>
{result.text}
</p>
)}
</div>
)
}
export { Example }支持的模式有 listbox、menu、menubar、tabs、radio-group、toolbar、tree、dialog、alertdialog、disclosure、accordion、combobox、slider、switch 和 checkbox。
检查会使用控件自己的按键,并在可能时恢复焦点和状态。检查菜单或对话框之前,先把它打开。菜单检查会激活一个选项,所以要用可以安全执行的测试动作。
它要求列表框、选项卡和工具栏支持 Home 和 End,要求每个选项卡列表都有名称,并要求模态对话框带有 aria-modal="true"。这些要求故意比 WAI-ARIA Authoring Practices 中部分可选行为更严格。
挂载原语
想测试原语本身时,使用 mount。传入它的定义、选项和一小段标记。与槽位匹配的标签会成为部件;它们的属性提供部件的 props。
这个测试使用确认按钮。第一次按压让它进入待命状态。再按一次则确认并解除待命:
import { expect, test } from "vitest"
import { mount } from "@ui-sdk/core/testing"
import { confirmButton } from "./confirm-button"
test("confirm with a click and Enter", async () => {
const button = mount(confirmButton, {}, `<root>Delete</root>`)
try {
await button.click(button.root)
expect(button.state.armed).toBe(true)
expect(button.changes.at(-1)).toMatchObject({
key: "armed",
reason: "press",
source: "mouse",
})
await button.keys("Enter")
expect(button.state.armed).toBe(false)
} finally {
button.unmount()
}
})import * as React from "react"
import { mount } from "@ui-sdk/core/testing"
import { confirmButton } from "./confirm-button"
type Check = { label: string; ok: boolean }
async function test() {
const checks: Check[] = []
const expect = (label: string, ok: boolean) => checks.push({ label, ok })
const button = mount(confirmButton, {}, `<root>Delete</root>`)
try {
await button.click(button.root)
expect("A click arms the button", button.state.armed)
const change = button.changes.at(-1)
expect("The change says why: press", change?.reason === "press")
expect("And how: mouse", change?.source === "mouse")
await button.keys("Enter")
expect("Enter confirms, and disarms it", !button.state.armed)
expect("From the keyboard", button.changes.at(-1)?.source === "keyboard")
expect(
"The button is a button",
button.part("root")!.getAttribute("type") === "button"
)
} finally {
button.unmount()
}
return checks
}
function Example() {
const [checks, setChecks] = React.useState<Check[] | null>(null)
return (
<div data-slot="stack">
<button
type="button"
data-variant="solid"
onClick={async () => setChecks(await test())}
>
Run the Test
</button>
{checks && (
<ul aria-label="Results" data-slot="list">
{checks.map((check) => (
<li key={check.label} data-slot="test-result" data-ok={check.ok}>
{check.ok ? "✓" : "✗"} {check.label}
</li>
))}
</ul>
)}
</div>
)
}
export { Example }root 是标记中的第一个元素。用 part(slot, key) 找到另一个部件,例如 view.part("item", "pear")。state 读取当前状态,api 暴露原语的方法,changes 记录每一次被接受的变更。
完成后一定要调用 unmount。它会移除标记、解绑部件并销毁实例。
输入、悬停与播报
调用 type 之前先聚焦输入框。特殊按键和组合键用 keys,包括 Tab、Shift+Tab 和 Space:
const search = mount(
searchField,
{},
`<root><input aria-label="Search"></input></root>`
)
try {
search.part("input")!.focus()
await search.type("pear")
expect(search.state.query).toBe("pear")
await search.keys("Escape")
expect(search.state.query).toBe("")
} finally {
search.unmount()
}对于指针交互,hover(element) 把指针移到部件上。drag(element, { to: target }) 拖到另一个元素;drag(element, { by: { x, y } }) 按距离移动。
import * as React from "react"
import { mount } from "@ui-sdk/core/testing"
import { searchField } from "./search-field"
import { seats } from "./seats"
import { subscribe } from "./subscribe-form"
type Check = { label: string; ok: boolean }
async function test() {
const checks: Check[] = []
const expect = (label: string, ok: boolean) => checks.push({ label, ok })
const search = mount(
searchField,
{},
`<root><input aria-label="Search"></input><clear>Clear</clear></root>`
)
try {
search.part("input")!.focus()
await search.type("pear")
expect("Typing sets the query", search.state.query === "pear")
await search.keys("Escape")
expect("Escape clears it", search.state.query === "")
} finally {
search.unmount()
}
const map = mount(
seats,
{},
`<root><seat value="A1"></seat><seat value="A2"></seat></root>`
)
try {
await map.hover(map.part("seat", "A2")!)
expect(
"Hovering a seat marks it",
map.part("seat", "A2")!.hasAttribute("data-hovered")
)
} finally {
map.unmount()
}
const form = mount(
subscribe,
{},
`<root as="form"><input as="input"></input><button type="submit">Subscribe</button><error></error></root>`
)
try {
await form.click(form.root.querySelector("button")!)
await form.settle()
expect(
"An empty email is announced",
form.announced.includes("Enter an email address")
)
} finally {
form.unmount()
}
return checks
}
function Example() {
const [checks, setChecks] = React.useState<Check[] | null>(null)
return (
<div data-slot="stack">
<button
type="button"
data-variant="solid"
onClick={async () => setChecks(await test())}
>
Run the Tests
</button>
{checks && (
<ul aria-label="Results" data-slot="list">
{checks.map((check) => (
<li key={check.label} data-slot="test-result" data-ok={check.ok}>
{check.ok ? "✓" : "✗"} {check.label}
</li>
))}
</ul>
)}
</div>
)
}
export { Example }announced 捕获原语发送给屏幕阅读器播报器的文本。检查延迟播报之前,先用 settle 等待已排期的工作:
await form.click(form.root.querySelector("button")!)
await form.settle()
expect(form.announced).toContain("Enter an email address")settle 会等待微任务、一轮定时器和两帧动画。如果你需要 devtools 上报的分组变更,请读取 settled;changes 保留每一次中间变更。
服务器返回的 HTML
checkServer 在没有 DOM 的情况下渲染传入的部件并返回 HTML。它会检查创建原语时没有读取浏览器全局对象、时钟或随机数,也会检查部件的属性、公开状态和存在性没有读取这些内容或选项:
import { checkServer } from "@ui-sdk/core/testing"
const html = checkServer(
readMore,
{},
`<root><trigger>Read more</trigger><panel>More</panel></root>`
)这里使用 read-more 原语。如果检查发现某个依赖可能导致部件在服务端和客户端渲染结果不同,它就会抛出错误:
import * as React from "react"
import { definePrimitive } from "@ui-sdk/core"
import { checkServer } from "@ui-sdk/core/testing"
import { readMore } from "./read-more"
const clock = definePrimitive({
name: "clock",
state: () => ({}),
api: () => ({}),
slots: (slot) => ({
root: slot({ attrs: () => ({ "data-rendered": String(Date.now()) }) }),
}),
})
function run(broken: boolean) {
try {
const html = broken
? checkServer(clock, {}, `<root>Now</root>`)
: checkServer(
readMore,
{},
`<root><trigger>Read more</trigger><panel>More</panel></root>`
)
return { ok: true, text: html }
} catch (error) {
return { ok: false, text: (error as Error).message }
}
}
function Example() {
const [broken, setBroken] = React.useState(false)
const [result, setResult] = React.useState<{
ok: boolean
text: string
} | null>(null)
return (
<div data-slot="check">
<div data-slot="row">
<button
type="button"
data-variant="solid"
onClick={() => setResult(run(broken))}
>
Check the Server HTML
</button>
<label data-slot="label">
<input
type="checkbox"
checked={broken}
onChange={(event) => {
setBroken(event.target.checked)
setResult(null)
}}
/>
Read the clock in attrs
</label>
</div>
{result && (
<pre
role="status"
data-slot="check-result"
data-status={result.ok ? "pass" : "fail"}
>
{result.text}
</pre>
)}
</div>
)
}
export { Example }标记遵循与 mount 相同的规则。普通 HTML 标签保持原样。例如,当某个槽位需要渲染特定标签时,使用 as="form"。
两个方向
对于使用水平方向键导航的控件,checkDirection 会比较从左到右和从右到左的行为。每次检查都会挂载一个新实例,按 Tab 进入其中,然后比较按下方向键之后的焦点和状态:
import { checkDirection } from "@ui-sdk/core/testing"
await checkDirection(pager, {}, `<root>Page</root>`)从右到左文本中的 Left 应与从左到右文本中的 Right 一致,反之亦然。当从左到右文本中的 Right 不起作用时,检查也会失败,因为没有可比较的移动。
import * as React from "react"
import { definePrimitive } from "@ui-sdk/core"
import { checkDirection } from "@ui-sdk/core/testing"
import { pager } from "./page-stepper"
const fixedPager = definePrimitive({
name: "pager",
state: () => ({ page: 1 }),
api: (context) => ({
keydown(event: KeyboardEvent) {
const by = { ArrowRight: 1, ArrowLeft: -1 }[event.key]
if (by) {
context.store.set({
page: Math.min(5, Math.max(1, context.store.get().page + by)),
})
}
},
}),
slots: (slot) => ({
root: slot({
attrs: () => ({ role: "spinbutton", tabindex: "0" }),
on: { keydown: (event, { api }) => api.keydown(event) },
}),
}),
})
function Example() {
const [broken, setBroken] = React.useState(false)
const [result, setResult] = React.useState<{
ok: boolean
text: string
} | null>(null)
async function check() {
try {
await checkDirection(broken ? fixedPager : pager, {}, `<root>Page</root>`)
setResult({
ok: true,
text: "Passes: the arrows swap in right-to-left text.",
})
} catch (error) {
setResult({ ok: false, text: (error as Error).message })
}
}
return (
<div data-slot="check">
<div data-slot="row">
<button type="button" data-variant="solid" onClick={check}>
Check Both Directions
</button>
<label data-slot="label">
<input
type="checkbox"
checked={broken}
onChange={(event) => {
setBroken(event.target.checked)
setResult(null)
}}
/>
Ignore the direction
</label>
</div>
{result && (
<p
role="status"
data-slot="check-result"
data-status={result.ok ? "pass" : "fail"}
>
{result.text}
</p>
)}
</div>
)
}
export { Example }分页器示例展示了它如何从页面上读取方向。
读取部件
如果只想做针对性的渲染断言,可以创建实例并直接查看某个部件。这些辅助函数不需要 DOM:
import { partAttrs, partPresent, partState } from "@ui-sdk/core/testing"
const instance = readMore({ id: "more" })
try {
instance.api.toggle()
const trigger = instance.part("trigger", {})
expect(partAttrs(trigger)).toMatchObject({ "aria-expanded": "true" })
expect(partState(trigger)).toEqual({ open: true })
expect(partPresent(instance.part("panel", {}))).toBe(true)
} finally {
instance.destroy()
}partAttrs 读取 HTML 属性,partState 读取传给渲染函数的公开状态,partPresent 告诉你该部件是否应该渲染。
import * as React from "react"
import { partAttrs, partPresent, partState } from "@ui-sdk/core/testing"
import { readMore } from "./read-more"
function read(open: boolean) {
const instance = readMore({ id: "more" })
try {
if (open) {
instance.api.toggle()
}
const trigger = instance.part("trigger", {})
const panel = instance.part("panel", {})
return {
trigger: JSON.stringify(partAttrs(trigger)),
state: JSON.stringify(partState(trigger)),
panel: String(partPresent(panel)),
}
} finally {
instance.destroy()
}
}
function Example() {
const [open, setOpen] = React.useState(false)
const parts = read(open)
return (
<div data-slot="stack">
<label data-slot="label">
<input
type="checkbox"
checked={open}
onChange={(event) => setOpen(event.target.checked)}
/>
Open it
</label>
<dl data-slot="read-parts-list">
<dt>partAttrs(trigger)</dt>
<dd data-attrs>{parts.trigger}</dd>
<dt>partState(trigger)</dt>
<dd data-state>{parts.state}</dd>
<dt>partPresent(panel)</dt>
<dd data-present>{parts.panel}</dd>
</dl>
</div>
)
}
export { Example }选择平台
快捷键标签在 Apple 平台上使用 Command,在其他平台上使用 Control。测试它们时显式设置平台,这样运行测试的机器就不会改变结果:
import { formatShortcut } from "@ui-sdk/core"
import { setPlatform } from "@ui-sdk/core/testing"
setPlatform("apple")
expect(formatShortcut("mod+b")).toContain("⌘B")
setPlatform("other")
expect(formatShortcut("mod+b")).toContain("Ctrl+B")这个覆盖设置对后续测试持续生效。在测试设置中设置它,让每个测试都得到它期望的平台。
在框架中测试
需要检查组件的标记、props 或它与周围 UI 的集成时,请通过框架的测试工具来渲染。方法相同:先交互,再读取结果。你也可以把渲染出的元素传给 checkPattern。
与 mount 不同,框架渲染器不会填补 DOM 测试环境中的缺失功能。对于只需要浮层能渲染的测试,jsdom 环境可以提供这几个小桩:
HTMLElement.prototype.showPopover ??= function () {}
HTMLElement.prototype.hidePopover ??= function () {}
Element.prototype.getAnimations ??= () => []
document.head.append(
Object.assign(document.createElement("style"), {
textContent: "[popover] { display: block !important }",
})
)这些桩不会真正执行原生浮层或动画行为。这类检查请用浏览器,用键盘和屏幕阅读器检查完成后的组件时也是如此。
有些东西会在渲染或事件之后稍晚一点才到位。只有图标的按钮会在渲染后过一拍才从它的 tooltip 得到名称,按压打开的菜单会在下一帧把焦点移入其中。用 settle 等待它们,在 React 中放在 act 里,或者用 findByRole 查询:
import { checkPattern, settle } from "@ui-sdk/core/testing"
await user.click(screen.getByRole("button", { name: "Options" }))
await act(settle)
await checkPattern(screen.getByRole("menu"), "menu")