puppeteer:单击 shadowroot 中的按钮

R. *_*sen 5 web-component typescript jestjs web-component-tester puppeteer

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

从 chrome 控制台,我可以执行以下操作:

document.getElementsByTagName('my-component')[0].shadowRoot.querySelector('#my-button').click()
Run Code Online (Sandbox Code Playgroud)

我正在努力与 puppeteer 做同样的事情。

  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();
    });
  });
Run Code Online (Sandbox Code Playgroud)

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

Dan*_*iel 13

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

在 Chrome 72(当前的 Canary)中,我们引入了一个新选项 - “复制 JS 路径”,位于“复制选择器”选项旁边:

啊啊

使用 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();
    });
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,这确实暴露了影子 DOM。现在您还可以使用“pierce”,就像“const the_elem = wait elem_parent.$('pierce/div.the_elem');” (3认同)

小智 5

这个问题可以通过Puppetterer 中的 P 选择器解决。

在这种情况下,您可以使用page.click('>>> #my-button'). 允许>>>您选择 ShadowRoots 中的内容。

我知道这个问题很旧,但我需要这个,并且这个问题仍然会在搜索中弹出。