puppeteer:点击 shadowroot 中的按钮

puppeteer: clicking button in shadowroot

我在测试上下文中对 shadowroot 中的元素执行操作时遇到困难。假设我有一个 Web 组件 <my-component />,它包含一个按钮 <input id="my-button" type="submit" />

在 chrome 的控制台中,我可以执行以下操作:

document.getElementsByTagName('my-component')[0].shadowRoot.querySelector('#my-button').click()

我正在为木偶师做同样的事情而苦苦挣扎。

  it('should click the button', async () => {
    await page.goto(`https://localhost:${port}`, {
      waitUntil: ['networkidle0', 'load'],
    });

    await page.$eval('my-component', (el: Element) => {
      el.shadowRoot.querySelector('#my-button').click();
    });
  });

单击该按钮应该会向我的服务器发出一个 http 请求,该请求会检索一些数据,然后我想在 dom 中断言这些数据。该请求永远不会触发。建议?

根据 Puppeteer Team 的评论,正确的方法是使用 JS 路径:

In Chrome 72 (current Canary) we introduced a new option - "Copy JS Path", located right next to the "Copy Selector" option:

使用 JS 路径的示例:

    it('should click the button', async () => {
      await page.goto(`https://localhost:${port}`, {
        waitUntil: ['networkidle0', 'load'],
      });
    
      const button = await (await page.evaluateHandle(`<JS-path-here>`)).asElement();
      button.click();
    });