You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Playwright测试聊天应用的Enter/Shift+Enter及API请求状态

聊天应用Enter/Shift+Enter行为的Playwright测试方案

测试前准备

测试开始前需设置API请求拦截,用于验证消息发送请求的触发状态。


测试1:按下Enter应发送消息并触发API请求

test("pressing enter should send message", async ({ page }) => {
  await page.goto("/chat");

  // 拦截消息发送API请求,替换为你应用实际的请求路径
  const sendRequestPromise = page.waitForRequest("/api/send-message");

  const input = page.getByRole("textbox");
  await input.fill("foo");
  await input.press("Enter");

  // 根据应用实际逻辑调整:若发送后输入框清空,改为toHaveValue("")
  await expect(input).toHaveValue("foo");

  // 验证API请求已触发
  const request = await sendRequestPromise;
  expect(request.method()).toBe("POST");
  // 验证请求体内容正确
  const requestBody = await request.postDataJSON();
  expect(requestBody.message).toBe("foo");

  // 可选:验证消息已显示在聊天列表中
  await expect(page.getByText("foo")).toBeVisible();
});

测试2:按下Shift+Enter应添加换行符且不触发API请求

test("pressing shift+enter should create a line break", async ({ page }) => {
  await page.goto("/chat");

  // 监听请求,标记是否触发了消息发送API
  let sendRequestTriggered = false;
  page.on("request", (request) => {
    if (request.url().includes("/api/send-message")) {
      sendRequestTriggered = true;
    }
  });

  const input = page.getByRole("textbox");
  await input.fill("foo");
  await input.press("Shift+Enter");

  // 兼容不同系统的换行符格式(\n或\r\n)
  await expect(input).toHaveValue(/foo(\r\n|\n)/);

  // 验证未触发消息发送API
  expect(sendRequestTriggered).toBe(false);
});

关键说明

  • API路径适配:将代码中的/api/send-message替换为你应用实际的消息发送API路径。
  • 输入框状态调整:如果你的应用在发送消息后会清空输入框,需将第一个测试中的await expect(input).toHaveValue("foo")改为await expect(input).toHaveValue("")。
  • 换行符兼容:使用正则表达式/foo(\r\n|\n)/可以兼容Windows和类Unix系统的换行差异,避免因环境不同导致测试失败。

内容的提问来源于stack exchange,提问作者Magnar Myrtveit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 09:14:59