Stenciljs E2E 测试:如何在阴影 Dom 中找到 child 的 child

Stenciljs E2E Testing: how to find a child of a child in the Shadow Dom

我的组件是这样排列的:

app-home
  shadow-root
    component1
      shadow-root
        div id=div1

换句话说,我的 app-home 和 component1 都有影子 dom。

我可以像这样在 Stenciljs E2E 测试中轻松找到组件 1:

const page = await newE2EPage();
await page.setContent('<app-home></app-home>');
const component1 = await page.find('app-home >>> component1');

但是,无论我尝试过什么,我都无法在 component1 中获取 #div1。取回 E2EElement 很重要,这样我就可以使用它的方法,例如在页面中触发更改的单击。

这是我尝试过的方法:

  1. page.find('app-home >>> component1 >>> #div1')

    Returns空

  2. component1.find(':host >>> #div1') 或 component1.find(':root >>> #div1') 或 component1.find( '>>> #div1') 或 component1.find('#div1') 或 component1.find('component1 >>> #div1')

    Returns空

  3. component1.shadowRoot.querySelector('#div1')

    此方法获取一个元素,但点击它或向其发送事件有 对页面中的 app-root 或 component1 没有影响。

当两个元素都有影子 dom 时,关于如何找到 child 的 child 有什么建议吗?

注意:我假设 component1 实际上是一个有效的自定义元素标签名称(包含破折号)。


page.find('app-home >>> component1 >>> #div1')

目前无法多次使用 >>>(请参阅 source)。 >>> 不是官方的 CSS 选择器,所以它的实现完全取决于 Stencil.js.


component1.find(':host >>> #div1')

这种方法或您的类似方法也不可行,因为在 E2EElement 上调用 .find 只能找到作为该元素子元素的元素,而不是宿主元素本身。


一个解决方案是完全切换到浏览器上下文:

await page.evaluate(() => {
  // this function will run in the browser context, not
  // in the Node.js context that the test is executed in.
  const appHome = document.querySelector('app-home');
  const comp1 = appHome.shadowRoot.querySelector('component1');
  const div1 = comp1.shadowRoot.querySelector('#div1');

  div1.click();
});

await page.waitForChanges();

您可以将其重构为帮助程序,但我同意如果 Stencil.js 为此提供适当的 API 会更好。多次允许 >>> 选择器将是一个不错的功能。我建议您在 Stencil.js 存储库中打开一个功能请求。