Playwright 触摸事件测试指南:用 Locator.dispatchEvent 模拟 Pan 与 Pinch 手势

原创2026-09-06 17:10:571,622 阅读
文章标签:测试质量保障开发工具浏览器控制GUI 自动化AI Agent

Playwright 触摸事件测试指南:用 Locator.dispatchEvent 模拟 Pan 与 Pinch 手势

本指南基于 Playwright 官方文档 触摸事件(legacy 触控 API) 编写,讲解如何针对仍在使用旧版 TouchEvent 响应滑屏、捏合、点按等手势的 Web 应用,通过 [method: Locator.dispatchEvent] 手动派发真实 TouchEvent 来完成手势测试。读完后你将掌握:如何用 dispatchEvent 构造 touchstart / touchmove / touchend 事件序列、触摸点坐标(clientX/clientY 与 pageX/pageY 等)如何设置、Playwright 在浏览器内核侧(注入脚本)如何把这些参数转换为真实的 Touch / TouchList 对象,以及 isTrusted 检查这一关键陷阱的处理方式。

一、为什么需要手动派发触摸事件

大多数 Web 应用已经改用 Pointer Events 或 TouchAction/CSS 级手势,但仍有不少应用(尤其是地图类、移动端 H5 应用)直接监听 touchstart、touchmove、touchend 这类旧版触摸事件来识别 swipe(滑动)、pinch(捏合)、tap(点按)。这类应用无法用 Playwright 的 page.touchscreen.tap() 之类的单点 API 覆盖复杂手势,官方文档给出的方案是:手动向页面元素派发 TouchEvent,并把 Touch 点对象作为 eventInit 参数传入。

两个关键前提(均来自文档与源码):

  1. dispatchEvent 派发的事件 Event.isTrusted 为 false。文档明确提醒:如果你的被测页面依赖 isTrusted === true(部分应用会用它判断是否拦截合成事件),需要在被测应用侧临时关闭 isTrusted 检查,否则派发的事件会被忽略。
  2. 建议启用移动设备上下文。文档示例统一使用 test.use({ ...devices['Pixel 7'] })(对应 hasTouch: true、isMobile: true 等),保证页面按移动环境渲染,手势行为更贴近真机。

二、底层机制:Playwright 如何把参数变成真实 TouchEvent

文档示例中的 locator.dispatchEvent('touchstart', { touches, changedTouches, targetTouches }) 并不是在测试进程里直接 new TouchEvent,而是一条跨进程调用链:

  • 客户端入口 Locator.dispatchEvent 把选择器、事件类型与 eventInit 转发给 Frame;
  • Frame.dispatchEvent 将 eventInit 序列化后经协议下发给浏览器端;
  • 浏览器内由注入脚本执行 InjectedScript.dispatchEvent:它先按事件类型查表(touchstart/touchmove/touchend/touchcancel 被归类为 'touch',见 事件类型映射表),然后构造一个默认 { bubbles: true, cancelable: true, composed: true } 的 eventInit,再把普通对象形式的触摸点转换为浏览器原生的 Touch 实例,最终 node.dispatchEvent(event) 派发。
// packages/injected/src/injectedScript.ts(节选,touch 分支)
case 'touch': {
  eventInit.target ??= node;
  eventInit.touches = eventInit.touches?.map((t) =>
    t instanceof Touch ? t : new Touch({ ...t, target: t.target ?? node }));
  eventInit.targetTouches = eventInit.targetTouches?.map(/* 同上 */);
  eventInit.changedTouches = eventInit.changedTouches?.map(/* 同上 */);
  event = new TouchEvent(type, eventInit);
}
node.dispatchEvent(event);

这里有两个值得注意的实现细节:

  1. 触摸点对象会被逐个 new Touch() 化,缺省的 target 自动取被派发事件的节点。所以文档示例里只需传 { identifier: 0, clientX, clientY } 这样的普通对象即可,target 由 Playwright 代劳。
  2. WebKit 有专门回退路径:源码注释 说明 WebKit 不支持 Touch 构造函数,因此改用已废弃的 document.createTouch / createTouchList;且 createTouch 不接受 clientX/clientY,源码会用 pageX = clientX + 页面滚动偏移 的方式自动换算。这正是文档中"In a more complex scenario you may need to also set pageX/pageY/screenX/screenY" 建议的由来——如果你的应用读取的是 pageX/pageY 或 screenX/screenY,请显式传入这些字段。

该行为在测试套件中也有直接验证:tests/library/locator-dispatchevent-touch.spec.ts 在 hasTouch: true 上下文下对 touchstart/touchmove/touchend 各派发两个触摸点,断言页面监听器收到的 Touch 对象的 identifier/clientX/clientY 与派发参数完全一致。

三、模拟 Pan(滑动)手势

官方示例:通过连续 touchmove 让 Google 地图发生位移,验证地图类应用对 pan 手势的响应。完整示例可参考 docs/src/touch-events.md。

3.1 事件序列结构

一次完整 pan 手势 = 1 个 touchstart + N 个 touchmove(坐标沿目标方向线性插值)+ 1 个 touchend(无参数,touches 为空):

touchstart ──► touchmove × steps ──► touchend
   (起点)        (逐步位移)           (抬手)

3.2 JavaScript / TypeScript 完整示例

import { test, expect, devices, type Locator } from '@playwright/test';

test.use({ ...devices['Pixel 7'] });

async function pan(locator: Locator, deltaX?: number, deltaY?: number, steps?: number) {
  const { centerX, centerY } = await locator.evaluate((target: HTMLElement) => {
    const bounds = target.getBoundingClientRect();
    const centerX = bounds.left + bounds.width / 2;
    const centerY = bounds.top + bounds.height / 2;
    return { centerX, centerY };
  });

  // Providing only clientX and clientY as the app only cares about those.
  const touches = [{
    identifier: 0,
    clientX: centerX,
    clientY: centerY,
  }];
  await locator.dispatchEvent('touchstart',
      { touches, changedTouches: touches, targetTouches: touches });

  steps = steps ?? 5;
  deltaX = deltaX ?? 0;
  deltaY = deltaY ?? 0;
  for (let i = 1; i <= steps; i++) {
    const touches = [{
      identifier: 0,
      clientX: centerX + deltaX * i / steps,
      clientY: centerY + deltaY * i / steps,
    }];
    await locator.dispatchEvent('touchmove',
        { touches, changedTouches: touches, targetTouches: touches });
  }

  await locator.dispatchEvent('touchend');
}

test(`pan gesture to move the map`, async ({ page }) => {
  await page.goto('https://www.google.com/maps/place/@37.4117722,-122.0713234,15z',
      { waitUntil: 'commit' });
  await page.getByRole('button', { name: 'Keep using web' }).click();
  await expect(page.getByRole('button', { name: 'Keep using web' })).not.toBeVisible();
  // Get the map element.
  const met = page.locator('[data-test-id="met"]');
  for (let i = 0; i < 5; i++)
    await pan(met, 200, 100);
  // Ensure the map has been moved.
  await expect(met).toHaveScreenshot();
});

参数说明:

参数 含义 默认值
deltaX / deltaY 本次 pan 的总位移量(视口坐标),沿元素中心方向移动 0
steps touchmove 事件数量,即位移被拆成多少步 5
identifier 触摸点标识,单指手势固定为 0 0

实现要点:

  • 起点取元素几何中心:JS 版本在页面内用 getBoundingClientRect() 计算中心点;C#/Java/Python 版本则用 boundingBox() 在测试进程内计算(centerX = x + width / 2),两者等价。
  • 位移线性插值:第 i 步坐标为 center + delta * i / steps,保证事件序列匀速推进,更贴近真实手指轨迹。
  • touches / changedTouches / targetTouches 三个字段都传同一份:单指手势中这三者内容一致;touchend 不传参数(默认空)。

3.3 Python 版本(sync 风格)

from playwright.sync_api import sync_playwright, expect

def pan(locator, deltaX=0, deltaY=0, steps=5):
    bounds = locator.bounding_box()
    centerX = bounds['x'] + bounds['width'] / 2
    centerY = bounds['y'] + bounds['height'] / 2

    touches = [{
        'identifier': 0,
        'clientX': centerX,
        'clientY': centerY,
    }]
    locator.dispatch_event('touchstart', {
        'touches': touches,
        'changedTouches': touches,
        'targetTouches': touches
    })

    for i in range(1, steps + 1):
        touches = [{
            'identifier': 0,
            'clientX': centerX + deltaX * i / steps,
            'clientY': centerY + deltaY * i / steps,
        }]
        locator.dispatch_event('touchmove', {
            'touches': touches,
            'changedTouches': touches,
            'targetTouches': touches
        })

    locator.dispatch_event('touchend')

def test_pan_gesture_to_move_the_map(page):
    page.goto('https://www.google.com/maps/place/@37.4117722,-122.0713234,15z', wait_until='commit')
    page.get_by_role('button', name='Keep using web').click()
    expect(page.get_by_role('button', name='Keep using web')).not_to_be_visible()
    met = page.locator('[data-test-id="met"]')
    for _ in range(5):
        pan(met, 200, 100)
    page.screenshot(path="screenshot.png")

with sync_playwright() as p:
    browser = p.chromium.launch()
    context = browser.new_context(**p.devices['Pixel 7'])
    page = context.new_page()
    test_pan_gesture_to_move_the_map(page)
    browser.close()

3.4 C# 与 Java 版本要点

文档同时提供了 C# 与 Java 的等价实现,结构完全一致,差异仅在设备上下文与断言写法:

// C#(节选)
var context = await browser.NewContextAsync(playwright.Devices["Pixel 7"]);
var met = page.Locator("[data-test-id='met']");
for (int i = 0; i < 5; i++)
    await Pan(met, 200, 100);
// Java(节选):未用 devices 表,而是显式设置 Pixel 7 的上下文参数
BrowserContext context = browser.newContext(new Browser.NewContextOptions()
  .setViewportSize(412, 839)
  .setDeviceScaleFactor(2.625)
  .setUserAgent("Mozilla/5.0 (Linux; Android 12; Pixel 7 Build/SP1A.210812.015) AppleWebKit/537.36" +
    " (KHTML, like Gecko) Chrome/94.0.4606.71 Mobile Safari/537.36")
  .setHasTouch(true)
  .setIsMobile(true)
);

注意 Java 示例把 viewportSize(412, 839)、deviceScaleFactor(2.625)、hasTouch(true)、isMobile(true) 显式列出——这就是 JS 端 devices['Pixel 7'] 展开后的核心参数,方便不依赖设备表的场景手工构造。

四、模拟 Pinch(捏合)手势

Pinch 用**两个触摸点相互靠近(zoom out)或远离(zoom in)**来表达。示例预期:两次手指捏拢使地图缩小。

import { test, expect, devices, type Locator } from '@playwright/test';

test.use({ ...devices['Pixel 7'] });

async function pinch(locator: Locator,
  arg: { deltaX?: number, deltaY?: number, steps?: number, direction?: 'in' | 'out' }) {
  const { centerX, centerY } = await locator.evaluate((target: HTMLElement) => {
    const bounds = target.getBoundingClientRect();
    const centerX = bounds.left + bounds.width / 2;
    const centerY = bounds.top + bounds.height / 2;
    return { centerX, centerY };
  });

  const deltaX = arg.deltaX ?? 50;
  const steps = arg.steps ?? 5;
  const stepDeltaX = deltaX / (steps + 1);

  // Two touch points equally distant from the center of the element.
  const touches = [
    {
      identifier: 0,
      clientX: centerX - (arg.direction === 'in' ? deltaX : stepDeltaX),
      clientY: centerY,
    },
    {
      identifier: 1,
      clientX: centerX + (arg.direction === 'in' ? deltaX : stepDeltaX),
      clientY: centerY,
    },
  ];
  await locator.dispatchEvent('touchstart',
      { touches, changedTouches: touches, targetTouches: touches });

  // Move the touch points towards or away from each other.
  for (let i = 1; i <= steps; i++) {
    const offset = (arg.direction === 'in' ? (deltaX - i * stepDeltaX) : (stepDeltaX * (i + 1)));
    const touches = [
      {
        identifier: 0,
        clientX: centerX - offset,
        clientY: centerY,
      },
      {
        identifier: 0,
        clientX: centerX + offset,
        clientY: centerY,
      },
    ];
    await locator.dispatchEvent('touchmove',
        { touches, changedTouches: touches, targetTouches: touches });
  }

  await locator.dispatchEvent('touchend', { touches: [], changedTouches: [], targetTouches: [] });
}

test(`pinch in gesture to zoom out the map`, async ({ page }) => {
  await page.goto('https://www.google.com/maps/place/@37.4117722,-122.0713234,15z',
      { waitUntil: 'commit' });
  await page.getByRole('button', { name: 'Keep using web' }).click();
  await expect(page.getByRole('button', { name: 'Keep using web' })).not.toBeVisible();
  // Get the map element.
  const met = page.locator('[data-test-id="met"]');
  for (let i = 0; i < 5; i++)
    await pinch(met, { deltaX: 40, direction: 'in' });
  // Ensure the map has been zoomed out.
  await expect(met).toHaveScreenshot();
});

关键参数与几何逻辑:

参数 含义
deltaX 两指相对中心的总移动幅度(示例中初始间距为 ±deltaX)
steps touchmove 步数,stepDeltaX = deltaX / (steps + 1) 为每步增量
direction: 'in' 双指向中心收拢(缩小/zoom out)
direction: 'out' 双指背离中心张开(放大/zoom in),touchstart 时从较小间距 ±stepDeltaX 出发

direction === 'in' 时第 i 步的偏移为 deltaX - i * stepDeltaX:从初始间距逐步递减至接近 0,两指"捏拢";'out' 时偏移为 stepDeltaX * (i + 1) 逐步增大,两指"张开"。

其他语言版本(C# Pinch(ILocator locator, int deltaX = 50, int steps = 5, string direction = "in")、Python pinch(locator, arg)、Java pinch(Locator locator, int deltaX, String direction))均实现同一套插值公式,完整代码见 docs/src/touch-events.md。

五、Touch 点坐标体系与多浏览器差异

需要设置哪些坐标? 文档建议:先只设 clientX/clientY(大多数应用只读这两个字段),如果应用还读取其他坐标再补 pageX/pageY/screenX/screenY。各坐标系区别:

  • clientX/clientY:相对视口(viewport)左上角;
  • pageX/pageY:相对整个文档(含滚动量);
  • screenX/screenY:相对物理屏幕。

跨内核实现差异(源码佐证):Chromium / Firefox 走标准 new Touch({...}) 构造;WebKit 分支(injectedScript.ts#L1186-L1208)因 createTouch 不接收 clientX/clientY,会自动以 clientX + document.scrollingElement.scrollLeft 换算出 pageX 再构造。因此:

  • 在 Chromium/Firefox 上,只传 clientX/clientY 即可;
  • 在 WebKit 上即使只传 clientX/clientY,pageX/pageY 也会被自动补齐(前提是页面无滚动或滚动量可被 scrollingElement 反映);
  • 若被测应用直接读 screenX/screenY 或在复杂滚动容器内取 pageX/pageY,建议显式提供全部所需字段,避免依赖自动换算。

六、注意事项与验证手段

  1. isTrusted 陷阱:dispatchEvent 派发的事件 isTrusted === false。若被测代码里有 if (!event.isTrusted) return; 之类的守卫,手势会被静默丢弃。测试期间需让应用关闭该检查(文档原话:make sure to disable isTrusted check during the test)。
  2. 严格模式定位:Locator.dispatchEvent 内部以 strict: true 解析选择器(见 locator.ts#L125-L126),元素不唯一会直接报错,避免手势派发到错误目标。
  3. 事件默认冒泡:注入脚本构造的 eventInit 默认为 bubbles: true, cancelable: true, composed: true(injectedScript.ts#L1180),可跨 Shadow DOM 与 iframe 传播,与真实触摸事件行为一致。
  4. touchend 的三种传法:pan 示例中 touchend 不传参数;pinch 示例中显式传空数组 { touches: [], changedTouches: [], targetTouches: [] };单指结束的严格语义可参考 locator-dispatchevent-touch.spec.ts——touches: [](当前仍在触摸)、changedTouches: touches(本次变化)、targetTouches: []。
  5. 验证方式:官方示例用 await expect(met).toHaveScreenshot() 对比截图确认地图确实被移动/缩小;CI 中也可先用 page.screenshot() 留证(如 C#/Python 示例),再人工或像素比对确认结果。
  6. 适用前提:此方案针对旧版 Touch Events(文档标题即标注 legacy)。如果应用改用 Pointer Events,page.touchscreen / locator.tap() 等更高层 API 往往更简单可靠。

七、小结

场景 方法 触摸点
Pan(滑动) touchstart → steps 次 touchmove → touchend 单指 identifier: 0,坐标线性插值
Pinch(捏合) 同上,但每步携带两个触摸点 identifier: 0/1,围绕元素中心对称收拢/张开

Playwright 的 dispatchEvent 把"手工构造 TouchEvent"这一繁琐工作封装成了"传普通对象即可":注入脚本负责把 { identifier, clientX, clientY } 转成浏览器原生 Touch/TouchList,并对 WebKit 做了 createTouch 回退。理解了这条链路后,你可以按同一模板扩展任意复合手势(旋转、拖拽、双击点按等),只需控制每步 touches 的坐标与数量即可。

登录后查看全文
playwright