4

尝试测试一些拖放功能,看起来 playwright 没有拖放功能,所以我正在使用mouse.move(), mouse.down()& mouse.up()

然而,我的尝试似乎失败了,目标没有被移动。下面的代码:

test("drag and drop test", async () => {
  await page.goto("https://www.w3schools.com/html/html5_draganddrop.asp");
  await page.waitForSelector("#accept-choices");
  await page.click("#accept-choices");
  await page.waitForSelector("#div1");
  let xStart, yStart, xFinish, yFinish, elementHandle, rect;
  elementHandle = await page.$("#div1");
  rect = await elementHandle.boundingBox();
  xStart = rect.x + rect.width / 2;
  yStart = rect.y + rect.height / 2;
  elementHandle = await page.$("#div2");
  rect = await elementHandle.boundingBox();
  xFinish = rect.x + rect.width / 2;
  yFinish = rect.y + rect.height / 2;
  console.log(`move from (${xStart}, ${yStart}) to (${xFinish},${yFinish})`);
  await page.screenshot({ path: "before drag.png" });
  await page.mouse.move(xStart, yStart);
  await page.mouse.down();
  await page.mouse.move(xFinish, yFinish);
  await page.mouse.up();
  await page.screenshot({ path: "after drag.png" });
});
4

2 回答 2

7

我也一直在为如何让drag and drop剧作家成为可能而苦苦挣扎。

例如,我需要垂直移动,

重新排序前 1 2 3

重新排序后应用 2 1 3

    const exampleOneDrag = await page.$(
      `[data-testid="${exampleOne}-drag-icon-button"]`
    )
    const exampleTwoDrag = await page.$(
      `[data-testid="${exampleTwo}-drag-icon-button"]`
    )
    const oneBoundingBox = await exampleOneDrag?.boundingBox()
    const twoBoundingBox = await exampleTwoDrag?.boundingBox()

    if (oneBoundingBox && twoBoundingBox) {
      await page.mouse.move(
        oneBoundingBox.x + oneBoundingBox.width / 2,
        oneBoundingBox.y + oneBoundingBox.height / 2,
        { steps: 5 }
      )
      await page.mouse.down()
      await page.mouse.move(
        twoBoundingBox.x + twoBoundingBox.width / 2,
        twoBoundingBox.y + twoBoundingBox.height / 2,
        { steps: 5 }
      )
      await page.mouse.up()
    }

能够做到这一点的关键是steps:5选项。我不完全确定它的作用,但我从这里找到:https ://github.com/codeceptjs/CodeceptJS/blob/e815d82af028e904051b5b6c70873164e1df1bfd/lib/helper/Playwright.js#L2289-L2307e

希望这对你有用。我认为你的情况,你应该这样改变

  await page.mouse.move(xStart, xFinish);
  await page.mouse.down();
  await page.mouse.move(yStart, yFinish);
于 2020-11-09T06:18:12.107 回答
1

1.13.0 版为此添加了 API 方法。查看文档
从文档复制:

page.dragAndDrop(source, target[, options])

  • 来源:string
  • 目标:string
  • 选项:Object
    • forceboolean是否绕过可操作性检查。默认为假。
    • noWaitAfterboolean启动导航的操作正在等待这些导航发生并等待页面开始加载。您可以通过设置此标志来选择退出等待。您只需要在特殊情况下使用此选项,例如导航到无法访问的页面。默认为假。
    • timeoutnumber以毫秒为单位的最大时间,默认为 30 秒,传递 0 以禁用超时。可以使用browserContext.setDefaultTimeout(timeout)or page.setDefaultTimeout(timeout)方法更改默认值。
    • trial:boolean设置后,此方法仅执行可操作性检查并跳过操作。默认为假。等到元素准备好执行操作而不执行它时很有用。
  • 返回:Promise<void>
于 2021-07-22T11:50:41.637 回答