如何在 Puppeteer 中模糊输入元素?

14

我正在使用 Puppeteer 测试表单。该表单具有在输入元素的失去焦点事件(blur)发生时触发的验证。但是,Puppeteer 没有提供模拟 blur 元素的 API。

我尝试聚焦/点击 bodydiv 元素,但这样做无法触发我的 onBlur 验证。例如: page.click("body"), page.focus("body")

现在,我正在使用伪造点击图像来触发 blur 事件。但这不是一个好的方法。

export class LoginPage {
  constructor(private page: Page) {}

  async setup(): Promise<void> {
    await this.page.goto(MY_LOGIN_FORM);
  }

  async typeEmail(email: string): Promise<void> {
    await this.page.type("input[name=email]", email);
    await this.blur();
  }

  async typePassword(password: string): Promise<void> {
    await this.page.type("input[name=password]", password);
    await this.blur();
  }

  async clickLoginButton(): Promise<void> {
    await this.page.click("button");
  }

  private async blur(): Promise<void> {
    // HACK
    await this.page.click("img");
  }
}

有没有不需要hack的方式来模糊输入框?

2个回答

23

我认为使用$eval可能会更加简洁:

await page.$eval('input[name=email]', e => e.blur());

0
Johannes Kronmüller的答案是正确的。 如果您正在使用TypeScript,则应该对元素进行类型定义。 这是您应该使用的内容:
await page.$eval('input[name=email]', (e: HTMLInputElement) => e.blur());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接