首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >模板单元测试:访问深度嵌套的Shadow DOM组件

模板单元测试:访问深度嵌套的Shadow DOM组件
EN

Stack Overflow用户
提问于 2020-05-02 21:42:23
回答 1查看 739关注 0票数 0

我有一个包含一些嵌套元素的Stencil.js组件库,我正在进行单元测试

我正在使用模板提供的newSpecPage助手功能:

代码语言:javascript
复制
const page = await newSpecPage({
    components: [CustomFileInput, CustomPanel],
    html: `
      <custom-file-input multiple>                    
      </custom-file-input>
    `
});

CustomPanel组件嵌套在CustomFileInput组件中。要查询CustomPanel中的元素,必须先遍历Shadow DOM元素,然后才能成功运行querySelector()命令

代码语言:javascript
复制
// page.root is the CustomFileInput HTML Element
const customPanelElement = page.root.shadowRoot.querySelector('custom-panel');
const queriedElemnt = customPanelElement.shadowRoot.querySelector('panel-child')

我想知道有没有一种更简洁的方法来获得对CustomPanelpanel-child元素的引用,而不是向下查询组件?在上面的例子中,只有2个组件,当然还有更多的组件

EN

回答 1

Stack Overflow用户

发布于 2021-03-16 18:42:00

我假设您使用的是shadow:true,所以您必须使用page.root.shadowRoot.querySelector('custom-panel')

你能做的是,你可以在beforeEach块中赋值引用

代码语言:javascript
复制
   const customPanelElement;
   const queriedElemnt;
   const page;

   beforeEach(async () => {
    page = await newSpecPage({
    components: [CustomFileInput, CustomPanel],
    html: `
      <custom-file-input multiple>                    
      </custom-file-input>
    `,
      supportsShadowDom: true
    });
    //Create reference here so that it is available inside every test case
    customPanelElement = page.root.shadowRoot.querySelector('custom-panel');
    queriedElemnt = customPanelElement.shadowRoot.querySelector('panel-child')
  });
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61560334

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档