javascript - Stenciljs E2E 测试 : how to find a child of a child in the Shadow Dom

标签 javascript e2e-testing stenciljs

我的组件排列如下:

app-home
  shadow-root
    component1
      shadow-root
        div id=div1
换句话说,我的 app-home 和 component1 都有 shadow dom。
我可以在 Stenciljs E2E 测试中轻松找到 component1,如下所示:
const page = await newE2EPage();
await page.setContent('<app-home></app-home>');
const component1 = await page.find('app-home >>> component1');
但是,无论我尝试过什么,我都无法在 component1 中获得 #div1。取回 E2EElement 很重要,这样我就可以使用它的方法,例如 click 触发页面中的更改。
这是我尝试过的:
  • page.find('app-home >>> component1 >>> #div1')返回空
  • component1.find(':host >>> #div1')component1.find(':root >>> #div1')component1.find('>>> #div1')component1.find('#div1')component1.find('component1 >>> #div1')返回空
  • component1.shadowRoot.querySelector('#div1')此方法获取一个元素,但单击它或向它发送事件
    对页面中的 app-root 或 component1 没有影响。

  • 那么当两个元素都有shadowDOM时如何找到一个 child 的 child 有什么建议吗?

    最佳答案

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

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

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

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

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

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

    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 存储库中打开一个功能请求。

    关于javascript - Stenciljs E2E 测试 : how to find a child of a child in the Shadow Dom,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60804053/

    相关文章:

    javascript - 未收到 Firebase 云消息/通知。 JS

    javascript - 使用 .attr 更改 onMouseOver

    JavaScript GetUserMedia 在没有 HTTPS 的情况下使用带有本地主机的 Chrome

    javascript - 如何将参数注入(inject) TestCafé 测试?

    jsx - Stenciljs:找不到另一个组件

    typescript - 对象数组 Prop 装饰器 StencilJS

    javascript - 输出数据中存在的嵌套 Handlebar 助手

    javascript - 访问新网址 Cypress

    javascript - 在 Svelte 中导入 Stencil

    node.js - Nest.js 测试错误 : Using the "extends Logger" instruction is not allowed in Nest v8. 请改用 "extends ConsoleLogger"