如何在 playwright 中等待 JavaScript 完成

Jac*_*cob 14 javascript puppeteer playwright

我正在使用 Playwright 和 JavaScript 测试 UI。我的代码找到一个输入元素,有时可以是下拉菜单,有时是文本,有时是日期。为了解决这个问题,我分两步输入值。首先,我填充文本,然后单击 Tab 键来调用格式化元素中的值的 JavaScript。

await page.fill("#myID", inputText); 
await page.keyboard.press('Tab');  // this line trigger the JS

// continue to the next element 
Run Code Online (Sandbox Code Playgroud)

问题是,它没有等待 JavaScript 完成。我怎样才能等待 JS 完成然后代码继续。

小智 13

您可以等待对点击的一些反应(某些页面更改或发出 HTTP 请求),例如:


Ste*_*eve 8

使用page.waitFor...功能

当满足以page.waitFor (例如page.waitForFunction)开头的某些条件时,剧作家提供了一系列功能。可能page.waitForFunction是最通用的,因为您可以传递等待满足特定条件的自定义函数。

或者,使用超时

我认为你可以在页面上下文中使用setTimeoutwithpage.evaluate来等待其他 JavaScript 运行:

await page.evaluate(() => {
  // if this doesn't work, you can try to increase 0 to a higher number (i.e. 100)
  return new Promise((resolve) => setTimeout(resolve, 0));
});
Run Code Online (Sandbox Code Playgroud)

这可能相当于page.waitForTimeout(0),但我不确定。请注意,他们建议不要page.waitForTimeout在生产中使用。