自动化测试 / 系统课时
使用键盘与鼠标
使用键盘与鼠标
键盘和鼠标 API 适合验证快捷键、焦点导航、悬停轨迹、滚轮以及无法用普通表单动作表达的交互。本节把元素级按键和页面级鼠标操作组合起来,并用可观察状态验证按键与滚动都真正生效。
学习目标
- 使用
Locator.press()发送单键和跨平台快捷键组合。 - 理解
page.keyboard与元素级按键操作的适用边界。 - 使用
page.mouse.move()和page.mouse.wheel()完成坐标移动与滚轮交互。
优先把按键发送给明确元素
目标控件已知时,优先使用 Locator.press()。它会先让目标元素获得焦点,再发送按键,因此比依赖“当前焦点是谁”的全局键盘操作更稳定。快捷键可以写成 ControlOrMeta+A,在 Windows/Linux 上使用 Control,在 macOS 上使用 Meta。
普通文本输入通常使用 fill();只有页面逻辑依赖逐字符的 keydown、keypress 或 keyup 事件时,再使用 pressSequentially()。这样可以避免为了“看起来更像真人”而无意义地降低测试速度。
组合快捷键与滚轮
下面的示例先用快捷键全选输入框内容,再逐字符输入新值并按 Enter;随后把鼠标移动到可滚动区域,通过滚轮向下滚动。测试分别验证状态文本和滚动位置。
import { test, expect } from '@playwright/test';
test('use keyboard shortcuts and mouse wheel', async ({ page }) => {
// 构造同时包含键盘事件和局部滚动区域的页面。
await page.setContent(`
<input aria-label="搜索" value="Playwright">
<div id="status">ready</div>
<div id="scroller" style="height:80px; overflow:auto">
<div style="height:500px">long content</div>
</div>
<script>
const input = document.querySelector('input');
input.addEventListener('keydown', event => {
if (event.key === 'Enter') {
document.querySelector('#status').textContent = input.value;
}
});
</script>
`);
const input = page.getByLabel('搜索');
await input.press('ControlOrMeta+A');
await input.pressSequentially('keyboard demo');
await input.press('Enter');
const scroller = page.locator('#scroller');
const box = await scroller.boundingBox();
if (!box) throw new Error('scroller is not visible');
// page.mouse 使用视口坐标,先把指针移动到滚动容器内部。
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2, { steps: 5 });
await page.mouse.wheel(0, 160);
await expect(page.locator('#status')).toHaveText('keyboard demo');
// wheel 不代表滚动已经完成,轮询最终 scrollTop 更可靠。
await expect.poll(() => scroller.evaluate(element => element.scrollTop)).toBeGreaterThan(0);
console.log(`${await page.locator('#status').textContent()}|scrolled`);
});预期输出
keyboard demo|scrolled什么时候使用 page.keyboard
page.keyboard 作用于当前获得焦点的页面元素,适合测试跨多个控件持续按住修饰键的场景。例如需要保持 Shift 或 Control 状态穿过多次操作时,可以使用 keyboard.down() 按住,再用 keyboard.up() 释放。
如果按键只属于一个明确输入框、按钮或列表项,Locator 级的 press() 更容易读懂,也减少了焦点被弹窗、动画或前一步操作意外改变造成的脆弱性。
使用原始鼠标 API 的边界
page.mouse 使用相对于主视口左上角的 CSS 像素坐标。move() 适合验证自定义悬停、画布或需要经过中间位置的轨迹;wheel(deltaX, deltaY) 用于发送水平或垂直滚轮事件。标准按钮、链接和表单控件仍应优先使用 Locator 的 click()、hover() 等高层动作。
可靠的交互测试应优先表达“用户要操作哪个元素”,只有元素级动作无法描述真实行为时才下降到键盘焦点或鼠标坐标层。